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 discussed 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
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Detecting top nodes on a Social Network - The VoteRank Algorithm
- Types of Antialiasing Techniques
- Advantages and Disadvantages of Auto-CAD
- Introduction of BlueJ
- Correlation Vs Causation
- Reflection In 2D Graphics
- Introduction to Auto-CAD software
- Basic Illumination Models
Improved By : Akanksha_Rai