|
| 1 | +/* |
| 2 | +Given the Sorted Linked list head which contain duplicates, the task is |
| 3 | +to delete all the duplicate and make linked list such that every element |
| 4 | +appear just one time. |
| 5 | +Example: |
| 6 | +Original Linked list : 1 1 2 2 3 |
| 7 | +Answer : 1 2 3 |
| 8 | +*/ |
| 9 | + |
| 10 | +#include <bits/stdc++.h> |
| 11 | +using namespace std; |
| 12 | + |
| 13 | +// A linked list node |
| 14 | +class Node |
| 15 | +{ |
| 16 | + public: |
| 17 | + int data; |
| 18 | + Node *next; |
| 19 | +}; |
| 20 | + |
| 21 | +// Utility function to create a new Node |
| 22 | +void push(Node **head, int n_data) |
| 23 | +{ |
| 24 | + Node *newdata = new Node(); |
| 25 | + newdata->data = n_data; |
| 26 | + newdata->next = (*head); |
| 27 | + (*head) = newdata; |
| 28 | +} |
| 29 | + |
| 30 | +// Function to print nodes in a given linked list. |
| 31 | +void printlinkedlist(Node *temp) |
| 32 | +{ |
| 33 | + while (temp != NULL) |
| 34 | + { |
| 35 | + cout << "->" << temp->data; |
| 36 | + temp = temp->next; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// Function to delete duplicate nodes |
| 41 | +Node *delete_duplicates(Node *head) |
| 42 | +{ |
| 43 | + //initalize current to head |
| 44 | + Node *curr = head; |
| 45 | + // when curr and curr->next is not NULL |
| 46 | + // enter the loop |
| 47 | + while (curr && curr->next) |
| 48 | + { |
| 49 | + // if the adjacent nodes are found to be equal |
| 50 | + if (curr->next->data == curr->data) |
| 51 | + { |
| 52 | + // then point the curr->next to one step ahead |
| 53 | + // to the existing pointer. |
| 54 | + curr->next = curr->next->next; |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + // Until the current and current->next values are |
| 59 | + // not same, keep updating current |
| 60 | + curr = curr->next; |
| 61 | + } |
| 62 | + } |
| 63 | + return head; |
| 64 | +} |
| 65 | +int main() |
| 66 | +{ |
| 67 | + Node *head = NULL; |
| 68 | + int n; |
| 69 | + cout << "Enter number of Elements:"; |
| 70 | + cin >> n; |
| 71 | + cout << "Enter elements:"; |
| 72 | + for (int i = 0; i < n; i++) |
| 73 | + { |
| 74 | + int a; |
| 75 | + cin >> a; |
| 76 | + push(&head, a); |
| 77 | + } |
| 78 | + cout <<"Original Linked list:\n"; |
| 79 | + printlinkedlist(head); |
| 80 | + cout <<"\nNew Linked List:\n"; |
| 81 | + head = delete_duplicates(head); |
| 82 | + printlinkedlist(head); |
| 83 | +} |
| 84 | + |
| 85 | +/* |
| 86 | +Sample Input: |
| 87 | +Enter number of Elements:5 |
| 88 | +Enter elements:1 1 2 2 3 |
| 89 | +
|
| 90 | +Sample Output: |
| 91 | +Original Linked list: |
| 92 | +->3->2->2->1->1 |
| 93 | +New Linked List: |
| 94 | +->3->2->1 |
| 95 | +
|
| 96 | +Time-Complexity: O(n) |
| 97 | +Space-Complexity: O(1) |
| 98 | +*/ |
0 commit comments