MrainW's Home

All things come to those who wait!

0%

LeetCode 1019. Next Greater Node In Linked List

Question

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.

https://leetcode.com/problems/next-greater-node-in-linked-list/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[] nextLargerNodes(ListNode head) {
List<Integer> nums = new ArrayList<>();
for (ListNode cur = head; cur != null; cur = cur.next) nums.add(cur.val);
int n = nums.size();
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--){
while (!stack.isEmpty() && nums.get(i) >= stack.peek()) stack.pop();
res[i] = stack.isEmpty() ? 0 : stack.peek();
stack.push(nums.get(i));
}
return res;
}
}

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels