1
class Solution {
2
public:
3
// Recursive Approach
4
ListNode *deleteDuplicates(ListNode *head) {
5
// base case
6
if (head == NULL || head->next == NULL) return head;
7
// 1-1-2-3-3
8
// we are giving next pointer to recursion and telling it to get it done for
9
// me
10
ListNode *newNode = deleteDuplicates(head->next); // 1-2-3-3
11
// after recursion we will get-- 1-2-3
12

13
// now we will compare the head node with the newNode
14
// if both are same then return the newNode
15
// else return the current head
16
if (head->val == newNode->val)
17
return newNode;
18
else {
19
head->next = newNode;
20
return head;
21
}
22
}
23
};
24

25
class Solution {
26
public:
27
// Iterative Approach
28
ListNode *deleteDuplicates(ListNode *head) {
29
if (head == NULL || head->next == NULL) return head;
30

31
ListNode *temp = head;
32
while (temp->next != NULL) {
33
// if the 2 consecutive nodes are equal then just delete the in between
34
if (temp->val == temp->next->val) {
35
temp->next = temp->next->next;
36
// dont need to update the temp variable as there can be more than 2
37
// duplicates
38
// 1-1-1-1-2-3-4-4-NULL
39
} else {
40
temp = temp->next; // update the temp variable
41
}
42
}
43
return head;
44
}
45
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0