700101. Delete nodes having greater value on right

Easy

Delete nodes having greater value on right

Summary

Given a linked list, delete all nodes that have a greater value to their right. For example, if the input linked list is 1 -> 2 -> 3 -> 4 -> 5, the output should be 1 -> 2 -> 3. This problem involves manipulating a linked list and finding nodes with specific values.

Detailed Explanation

The approach to solve this problem is to iterate through the linked list, comparing each node's value to the value of its next node. If the current node has a greater value than its next node, we delete it. We repeat this process until the end of the list is reached.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, curr and prev, to the head of the linked list.
  2. Iterate through the linked list while curr is not null.
  3. If curr->next is not null, compare the values of curr and curr->next. If curr->val > curr->next->val, delete curr.
  4. Move curr to curr->next and update prev if necessary (i.e., if we deleted a node).
  5. Repeat steps 2-4 until the end of the list is reached.
  6. Return the modified linked list.

Here's an ASCII art diagram to illustrate the process:

         1 -> 2 -> 3 -> 4 -> 5
          ^           ^
          |           |
        delete 3     delete 4
         1 -> 2 -> 3 -> 4 -> 5 (before)
         1 -> 2 -> 5 (after)

The time complexity of this algorithm is O(n), where n is the length of the linked list. The space complexity is O(1) because we only use a constant amount of space to store the pointers and variables.

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public ListNode deleteNodes(ListNode head) {
        ListNode curr = head;
        while (curr != null && curr.next != null) {
            if (curr.val > curr.next.val) {
                curr.next = curr.next.next;
            } else {
                curr = curr.next;
            }
        }
        return head;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.