Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5 Output: 1->2->5
Example 2:
Input: 1->1->1->2->3 Output: 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) {
if(head==NULL) return head;
ListNode helper(0);
ListNode* cur=head;
ListNode* pre = &helper;
helper.next = cur;
while(cur!=NULL){
while(cur->next!=NULL&&cur->val==cur->next->val){
cur = cur->next;
}
if(pre->next == cur) pre = pre->next;
else pre->next = cur->next;
cur = cur->next;
}
return helper.next;
}
};