[LeetCode] 082: Remove Duplicates from Sorted List

来源:互联网 发布:点餐系统数据库设计 编辑:程序博客网 时间:2024/05/21 12:40
[Problem]

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.


[Solution]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// null node
if(NULL == head) return NULL;

// delete duplicates
ListNode *pre = head;
ListNode *p = head->next;
while(p != NULL){
if(pre->val == p->val){
pre->next = p->next;
p = p->next;
}
else{
pre = p;
p = p->next;
}
}
return head;
}
};
说明:版权所有,转载请注明出处。Coder007的博客