Skip to content

1072. Next Greater Node In Linked List

Difficulty: Medium

LeetCode Problem View on GitHub


1072. Next Greater Node In Linked List

Medium


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.

 

Example 1:

Input: head = [2,1,5]
Output: [5,5,0]

Example 2:

Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]

 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= n <= 104
  • 1 <= Node.val <= 109

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int[] nextLargerNodes(ListNode head) {
        ArrayList<Integer> nodes = new ArrayList<>();
        ListNode current = head;
        while (current != null) {
            nodes.add(current.val);
            current = current.next;
        }
        Stack<Integer> st = new Stack<>();
        int res[] = new int[nodes.size()];
        for (int i = nodes.size() - 1; i >= 0; i--) {
            int curr = nodes.get(i);
            while (st.size() > 0 && st.peek() <= curr) st.pop();
            if (st.size() == 0) res[i] = 0;
            else res[i] = st.peek();
            st.add(curr);
        }
        return res;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here