Given a doubly linked list. The problem is to remove all adjacent duplicate nodes from the list such that the final modified doubly linked list does not contain any adjacent duplicate nodes.
Approach: The approach uses stack to keep track of the adjacent nodes at any point in the modified Doubly Linked List.
delAdjacentDuplicates(head_ref) Create an empty stack st Declare current, next, top current = head_ref while current != NULL if isEmpty(st) or current->data != peek(st)->data push current on to the stack st current = current->next else next = current->next top = peek(st) pop element from st delete node 'current' delete node 'top' current = next
peek(st) operation returns the value at the top of the stack. The algorithm to delete a node n from the doubly linked list using pointer to the node n is diccussed in this post.
Doubly linked list before deletion: 10 8 4 4 8 5 Doubly linked list after deletion: 10 5
Time Complexity: O(n)
Auxiliary Space: O(n), in worst case when there are no adjacent duplicate nodes.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Make middle node head in a linked list
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- How to insert elements in C++ STL List ?
- Self Organizing List : Transpose Method
- How to Prepare a Word List for the GRE General Test
- Optimal read list for given number of days
- Difference between LED and LCD
- Difference between Function and Procedure
- JBIG2 compression
- Difference between Information and Knowledge
- Cloud Deployment Model
- Basics of Input and Output in Windows PowerShell
- Random-Scan Display
- Raster-Scan Displays