Skip to content

1019. Next Greater Node In Linked List 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  vector<int> nextLargerNodes(ListNode* head) {
    vector<int> ans;
    stack<int> stack;

    for (; head; head = head->next) {
      while (!stack.empty() && head->val > ans[stack.top()]) {
        int index = stack.top();
        stack.pop();
        ans[index] = head->val;
      }
      stack.push(ans.size());
      ans.push_back(head->val);
    }

    for (; !stack.empty(); stack.pop())
      ans[stack.top()] = 0;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int[] nextLargerNodes(ListNode head) {
    List<Integer> ans = new ArrayList<>();
    Deque<Integer> stack = new ArrayDeque<>();

    for (; head != null; head = head.next) {
      while (!stack.isEmpty() && head.val > ans.get(stack.peek())) {
        int index = stack.pop();
        ans.set(index, head.val);
      }
      stack.push(ans.size());
      ans.add(head.val);
    }

    while (!stack.isEmpty())
      ans.set(stack.pop(), 0);

    return ans.stream().mapToInt(Integer::intValue).toArray();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def nextLargerNodes(self, head: ListNode) -> list[int]:
    ans = []
    stack = []

    while head:
      while stack and head.val > ans[stack[-1]]:
        index = stack.pop()
        ans[index] = head.val
      stack.append(len(ans))
      ans.append(head.val)
      head = head.next

    for i in stack:
      ans[i] = 0

    return ans