Leetcode: Remove Duplicates from Sorted List

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.

 1 class Solution {
 2 public:
 3     ListNode *deleteDuplicates(ListNode *head) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (!head) return NULL;
 7         ListNode *pre = head, *cur = head->next;
 8         while (cur) {
 9             if (cur->val == pre->val) {
10                 pre->next = cur->next;
11                 delete cur;
12                 cur = pre;
13             }
14             pre = cur;
15             cur = cur->next;
16         }
17 
18         return head;
19     }
20 };

 


 

posted @ 2013-05-01 22:07  caijinlong  阅读(168)  评论(0编辑  收藏  举报