Skip to main content
Back to problems
#1019
Medium Algorithms

Next greater node in linked list

Array Linked List Stack Monotonic Stack
63.9% acceptance
Feb 25, 2026
3524
127
You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn next_larger_nodes(head: Option<Box<ListNode>>) -> Vec<i32> {
    let mut vals = Vec::new();
    let mut cur = &head;
    while let Some(node) = cur { vals.push(node.val); cur = &node.next; }
    let mut ans = vec![0; vals.len()];
    let mut stack: Vec<usize> = Vec::new(); // indices
    for i in 0..vals.len() {
      while let Some(&top) = stack.last() {
        if vals[top] < vals[i] { ans[top] = vals[i]; stack.pop(); } else { break; }
      }
      stack.push(i);
    }
    ans
  }
}