# Javascript Program To Delete Nodes Which Have A Greater Value On Right Side

Last Updated : 30 Mar, 2022

Given a singly linked list, remove all the nodes which have a greater value on the right side.

Examples:

```Input: 12->15->10->11->5->6->2->3->NULL
Output: 15->11->6->3->NULL
Explanation: 12, 10, 5 and 2 have been deleted because there is a
greater value on the right side. When we examine 12,
we see that after 12 there is one node with a value
greater than 12 (i.e. 15), so we delete 12. When we
examine 15, we find no node after 15 that has a value
greater than 15, so we keep this node. When we go like
this, we get 15->6->3

Input: 10->20->30->40->50->60->NULL
Output: 60->NULL
Explanation: 10, 20, 30, 40, and 50 have been deleted because
they all have a greater value on the right side.

Input: 60->50->40->30->20->10->NULL
Output: No Change.```

Method 1 (Simple):
Use two loops. In the outer loop, pick nodes of the linked list one by one. In the inner loop, check if there exists a node whose value is greater than the picked node. If there exists a node whose value is greater, then delete the picked node.
Time Complexity: O(n^2)

Method 2 (Use Reverse):
Thanks to Paras for providing the below algorithm.
1. Reverse the list.
2. Traverse the reversed list. Keep max till now. If the next node is less than max, then delete the next node, otherwise max = next node.
3. Reverse the list again to retain the original order.
Time Complexity: O(n)
Thanks to R.Srinivasan for providing the code below.

## Javascript

 ``

Output:

```Given Linked List
12 15 10 11 5 6 2 3
15 11 6 3```

Time Complexity: O(n)

Auxiliary Space: O(1)

Method 3:
The other simpler method is to traverse the list from the start and delete the node when the current Node < next Node. To delete the current node, follow this approach.Let us assume you have to delete current node X:

1. Copy next node’s data into X i.e X.data = X.next.data.
2. Copy next node’s next address i.e X.next = X.next.next.

Move forward in the List only when the current Node is > the next Node.

## Javascript

 ``

Output:

```Given Linked List
12 15 10 11 5 6 2 3
15 11 6 3```

Time Complexity: O(n)

Auxiliary Space: O(1)

Please refer complete article on Delete nodes which have a greater value on right side for more details!

Previous Article
Next Article
Article Tags :
Practice Tags :