-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathRemoveDuplicatesfromSortedListII.cpp
69 lines (61 loc) · 1.4 KB
/
RemoveDuplicatesfromSortedListII.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
LINK: https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list-ii/
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::deleteDuplicates(ListNode* head)
{
if(head==NULL)
return head;
int pval = head->val;
ListNode *temp = NULL, *ptemp = head;
int cnt=1;
while(ptemp->next!=NULL)
{
if(ptemp->next->val == pval)
{
ptemp = ptemp->next;
cnt++;
}
else
{
if(cnt<=1)
{
if(temp==NULL)
head = temp = ptemp;
else
{
temp->next = ptemp;
temp = ptemp;
}
}
ptemp = ptemp->next;
pval = ptemp->val;
cnt=1;
}
}
if(cnt<=1)
{
if(temp==NULL)
head = temp = ptemp;
else
{
temp->next = ptemp;
temp = ptemp;
}
}
if(temp==NULL)
return temp;
temp->next=NULL;
return head;
}