07
05/2015
[LeetCode] Remove Duplicates from Sorted List
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
.
解题思路:
链表的一般技巧就是增加一个伪头结点,然后在返回的时候删除伪头结点即可,这样就能减少不同情况的讨论。
/** * 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) { ListNode* myHead=new ListNode(0); myHead->next = head; ListNode *p=myHead, *q; while(p->next!=NULL&&p->next->next!=NULL){ if(p->next->val == p->next->next->val){ q=p->next; p->next = p->next->next; delete q; }else{ p=p->next; } } p=myHead; myHead=myHead->next; delete p; return myHead; } };
二次刷题(2015-08-03)
/** * 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) { if(head == NULL){ return head; } ListNode* p = head, *q; while(p->next!=NULL){ if(p->next->val == p->val){ q = p->next; p->next = q->next; delete q; }else{ p=p->next; } } return head; } };
0 条评论