Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
» Solve this problemGiven
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.[解题思路]
同样是双指针,但是这里要注意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:
Post a Comment