Sunday, December 30, 2012

[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.
» Solve this problem

[解题思路]
同样是双指针,但是这里要注意delete不用的节点。

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





No comments: