-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathremove_duplicates_from_linked_list.cpp
86 lines (71 loc) · 1.75 KB
/
remove_duplicates_from_linked_list.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// 3rd July 2024
// Remove all occurences of duplicates in a linked list
/*
Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list, and return the head of the modified linked list.
Example1:
Input:
Linked List = 23->28->28->35->49->49->53->53
Output:
23 35
Example2:
Input:
Linked List = 11->11->11->11->75->75
Output:
Empty list
*/
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
class Solution {
public:
Node* removeAllDuplicates(struct Node* head) {
if(!head) return head;
if(!head->next || head->next->data != head->data) {
head->next = removeAllDuplicates(head->next);
return head;
}
int x = head->data;
while(head && head->data == x)
head = head->next;
return removeAllDuplicates(head);
}
};
void printList(struct Node *head) {
struct Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
int main() {
int T;
cin >> T;
while (T--) {
int N;
cin >> N;
Node *head = NULL;
Node *temp = head;
for (int i = 0; i < N; i++) {
int data;
cin >> data;
if (head == NULL)
head = temp = new Node(data);
else {
temp->next = new Node(data);
temp = temp->next;
}
}
Solution ob;
head = ob.removeAllDuplicates(head);
printList(head);
cout << "\n";
}
return 0;
}