File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < iostream>
2+ using namespace std ;
3+ struct Node {
4+ int data;
5+ Node * next;
6+ Node (int val): data(val), next(nullptr ) {}
7+ };
8+ Node * removeDuplicates (Node * head){
9+ if (head == NULL ){
10+ return NULL ;
11+ }
12+ Node * current = head;
13+ while (current != NULL ){
14+ Node * runner = current; // Use a runner to iterate from current->next
15+ while (runner->next != NULL ){ // Iterate until the second to last node
16+ if (runner->next ->data == current->data ){ // Check the next node's data
17+ Node * nodetodelete = runner->next ;
18+ runner->next = runner->next ->next ;
19+ delete nodetodelete;
20+ }
21+ else {
22+ runner = runner->next ;
23+ }
24+ }
25+ current = current->next ;
26+ }
27+ return head;
28+ }
29+ void printList (Node * head){
30+ Node * curr = head;
31+ while (curr != NULL ){
32+ cout << curr->data << " " ;
33+ curr = curr->next ;
34+ }
35+ cout << endl;
36+ }
37+ int main (){
38+ Node * head = new Node (5 );
39+ head->next = new Node (3 );
40+ head->next ->next = new Node (4 );
41+ head->next ->next ->next = new Node (3 );
42+ head->next ->next ->next ->next = new Node (5 );
43+ cout << " Original Linked List: " ;
44+ printList (head);
45+ head = removeDuplicates (head);
46+ cout << " Linked List After Removing Duplicates: " ;
47+ printList (head);
48+ return 0 ;
49+ }
You can’t perform that action at this time.
0 commit comments