Algorithm
Problem Name: 1019. Next Greater Node In Linked List
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
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int[] nextLargerNodes(ListNode head) {
// Reverse the list
ListNode curr = head;
ListNode prev = null;
ListNode next = null;
int count = 0;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
count++;
}
curr = prev;
Stack < Integer> stack = new Stack<>();
int[] ans = new int[count];
int idx = count - 1;
while (curr != null) {
// Keep track of next greatest value node
while (!stack.isEmpty() && stack.peek() < = curr.val) {
stack.pop();
}
ans[idx--] = stack.isEmpty() ? 0 : stack.peek();
stack.push(curr.val);
curr = curr.next;
}
return ans;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const nextLargerNodes = function(head) {
const A = []
while (head != null) A.push(head.val), (head = head.next)
const res = new Array(A.length).fill(0)
const stack = []
for (let i = 0; i < A.length; i++) {
while (stack.length && A[stack[stack.length - 1]] < A[i])
res[stack.pop()] = A[i]
stack.push(i)
}
return res
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
heap, res, j = [], [], 0
while head:
res.append(0)
while heap and heap[0][0] < head.val:
val, i = heapq.heappop(heap)
res[i] = head.val
heapq.heappush(heap, (head.val, j))
j += 1
head = head.next
return res
Copy The Code &
Try With Live Editor
Input
Output