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) {}
* };
*/
typedef ListNode node;
ListNode *deleteDuplicates(ListNode *head) {
if(!head || !head->next)return head;
ListNode *prev = NULL,*cur = head, *newHead = NULL;
while(cur)
{
node *nxt = cur->next;
bool deleteCur = false;
while(nxt && nxt->val == cur->val)
{
deleteCur = true;
node *tmp = nxt;
cur->next = nxt->next;
nxt = nxt->next;
delete tmp;
}
if(deleteCur)
{
node *tmp = cur;
if(prev)
prev->next = nxt;
cur = nxt;
if(nxt)
nxt = nxt->next;
delete tmp;
}
else
{
if(!prev)newHead = cur;
prev = cur;
cur = nxt;
if(nxt)
nxt = nxt->next;
}
}
return newHead;
}
No comments:
Post a Comment