Explanation
Let’s understand the above C++ code in detail.
Lines 1–13: This is the definition of the Node
class, it defines a node with an integer value and a pointer to the next node.
Lines 15–22: The LinkedList
class is defined. It has a constructor that initializes the head pointer to nullptr
.
Lines 24–29: The addNode
function adds a new node to the beginning of the linked list by creating a new node with the given value and updating the head
pointer.
Lines 31–38: The printList
function prints the values of all nodes in the linked list.
Lines 40–68: The deleteGreaterRight
function deletes nodes with values less than any value to their right in the list. It iterates through each node in the list and compares its value to the values of the subsequent nodes. If a greater value is found, it replaces the current node’s value with the greater value and removes the node with the greater value. It deallocates the memory for the removed node.
Lines 70–87: The main
function creates a LinkedList
object and adds several nodes to it. Then it prints the initial list, calls the deleteGreaterRight
function to modify the list, and finally prints the modified list.
Time complexity
The time complexity isO(n2). It exhibits quadratic time complexity due to the deleteGreaterRight
function having nested iterations which has a worst-case time complexity of O(n2).
Space complexity
The space complexity isO(1). The code maintains a constant space complexity by utilizing a fixed amount of memory irrespective of the size of the input.
Reversing the linked list
The reverse approach is an optimized solution to the problem. Instead of comparing each node with subsequent nodes, we reverse the linked list and iterate through it in reverse order. By doing so, we can track the maximum value seen so far while traversing the reversed list. Nodes with values greater than the maximum value are deleted.
Algorithm
Here’s how the algorithm works:
Reverse the linked list using the standard reversal technique.
Traverse the reversed list from left to right.
Maintain a variable to store the maximum value encountered.
Delete the node if the current node’s value is less than the maximum value.
Update the maximum value if the current node’s value is greater than the maximum value.
Reverse the linked list back to its original order (optional).
To reverse a linked list efficiently, read this short article: How to reverse a linked list in place.
Implementation
Below is the implementation of the algorithm in C++ and Python: