Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Given
1->2->3->3->4->4->5, return 1->2->5.Given
1->1->1->2->3, return 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* dummy =new ListNode(0);
dummy->next = head;
int val = INT_MIN;
ListNode *cur = head;
ListNode* pre = dummy;
while(cur)
{
if (cur->val == val || cur->next && cur->val == cur->next->val)
{
pre->next = cur->next;
val = cur->val;
delete cur;
cur=pre->next;
}
else
{
val = cur->val;
pre = cur;
cur = cur->next;
}
}
head = dummy->next;
delete dummy;
return head;
}
};
No comments:
Post a Comment