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 firstname.lastname@example.org. 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.
- Optimal read list for given number of days
- How to insert elements in C++ STL List ?
- Make middle node head in a linked list
- Self Organizing List : Transpose Method
- How to Prepare a Word List for the GRE General Test
- Relationship between Data Mining and Machine Learning
- Management Information System (MIS) Models
- Difference between a Data Analyst and a Data Scientist
- Case-specific sorting of Strings in O(n) time and O(1) space
- Pricing Models for Amazon EC2
- Management Information System (MIS)
- Paper Battery
- Difference between Management Information System (MIS) and Decision Support System (DSS)
- Storage Management