Remove all non-leader nodes from a given singly linked list | CODING INTERVIEW ARCHIVES
Given a singly linked list of integers, you have to delete all non-leaders nodes from the list. By leader we mean a node for which all the nodes to its right are smaller in value than this node.For example, in the list given as:
6 -> 9 -> 5-> 1
6 is a non-leader node as it has 9 in its right (which is greater than 6).
Algorithm:
Here, we are proposing a recursive solution for this problem.
- If this node is the last node, set max as its data and return this node.
- Recursively, call for its neighbor.
- If value of this node it smaller than max, delete this node.
- Else if value of this is larger than max, update max as value of this node.
Read full article from Remove all non-leader nodes from a given singly linked list | CODING INTERVIEW ARCHIVES
No comments:
Post a Comment