[LeetCode] Next Greater Node In Linked List

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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) {}
* };
*/
class Solution {
vector<int> res;
vector<int> st;
void helper(ListNode* node, int i) {
if(!node) return;
res.push_back(0);
helper(node->next, i + 1);
while(!st.empty() and st.back() <= node->val) st.pop_back();
if(!st.empty()) res[i] = st.back();
st.push_back(node->val);
}
public:
vector<int> nextLargerNodes(ListNode* head) {
helper(head, 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/03/PS/LeetCode/next-greater-node-in-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.