Remove duplicate values from a sorted linked list. For linked list problems, I’ve found that keeping track of before, now, and next pointers makes the logic much simpler.
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
| class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ListNode *headbackup = head;
int val = 0;
if(head == NULL)
{
return headbackup;
}
ListNode * before = head;
ListNode * now = head->next;
val = before->val;
while(now != NULL)
{
if(val != now->val)
{
val = now->val;
before = now;
now = now->next;
}
else
{
now = now->next;
before->next = now;
}
}
return headbackup;
}
};
|