LeetCode Solutions

1019. Next Greater Node In Linked List

Time:

Space:

			

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;
  }
};
			

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();
  }
}
			

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