# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def nextLargerNodes(self, head: ListNode) -> list[int]:
values = []
while head:
values.append(head.val)
head = head.next
result = [0] * len(values)
stack = []
for i, value in enumerate(values):
while stack and values[stack[-1]] < value:
idx = stack.pop()
result[idx] = value
stack.append(i)
return result
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
#include <vector>
#include <stack>
class Solution {
public:
std::vector<int> nextLargerNodes(ListNode* head) {
std::vector<int> values;
while (head) {
values.push_back(head->val);
head = head->next;
}
std::vector<int> result(values.size(), 0);
std::stack<int> stk;
for (int i = 0; i < values.size(); ++i) {
while (!stk.empty() && values[stk.top()] < values[i]) {
result[stk.top()] = values[i];
stk.pop();
}
stk.push(i);
}
return result;
}
};
// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
import java.util.*;
class Solution {
public int[] nextLargerNodes(ListNode head) {
List<Integer> values = new ArrayList<>();
while (head != null) {
values.add(head.val);
head = head.next;
}
int[] result = new int[values.size()];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < values.size(); i++) {
while (!stack.isEmpty() && values.get(stack.peek()) < values.get(i)) {
result[stack.pop()] = values.get(i);
}
stack.push(i);
}
return result;
}
}
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var nextLargerNodes = function(head) {
let values = [];
while (head) {
values.push(head.val);
head = head.next;
}
let result = new Array(values.length).fill(0);
let stack = [];
for (let i = 0; i < values.length; i++) {
while (stack.length && values[stack[stack.length - 1]] < values[i]) {
let idx = stack.pop();
result[idx] = values[i];
}
stack.push(i);
}
return result;
};
head
, return an array of integers result
where result[i]
is the value of the next node that is greater than the value of the i
-th node in the list. If there is no such node, result[i]
should be 0
.0
for that position.head = [2, 1, 5]
[2, 1, 5]
[0, 0, 0]
[]
[0]
[0, 1]
[2]
[5, 5, 0]