Remove all occurrences of duplicates from a sorted 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.
Examples:
Note that this is different from Remove Duplicates From Linked List
Remove duplicates from a sorted linked list
Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once.
For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates[] should convert the list to 11->21->43->60.
C
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 | #include #include // A Linked List Node struct Node { int data; struct Node* next; }; // Helper function to print a given linked list void printList[struct Node* head] { struct Node* ptr = head; while [ptr] { printf["%d —> ", ptr->data]; ptr = ptr->next; } printf["NULL"]; } // Helper function to insert a new node at the beginning of the linked list void push[struct Node** head, int data] { struct Node* newNode = [struct Node*]malloc[sizeof[struct Node]]; newNode->data = data; newNode->next = *head; *head = newNode; } // Remove duplicates from a sorted list void removeDuplicates[struct Node* head] { // do nothing if the list is empty if [head == NULL] { return; } struct Node* current = head; // compare the current node with the next node while [current->next != NULL] { if [current->data == current->next->data] { struct Node* nextNext = current->next->next; free[current->next]; current->next = nextNext; } else { current = current->next;// only advance if no deletion } } } int main[void] { // input keys int keys[] = {1, 2, 2, 2, 3, 4, 4, 5}; int n = sizeof[keys]/sizeof[keys[0]]; // points to the head node of the linked list struct Node* head = NULL; // construct a linked list for [int i = n-1; i >= 0; i--] { push[&head, keys[i]]; } removeDuplicates[head]; // print linked list printList[head]; return 0; } |
DownloadRun Code
Output:
1 —> 2 —> 3 —> 4 —> 5 —> NULL