-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnext_greater_node_in_ll.cpp
More file actions
51 lines (42 loc) · 1.09 KB
/
Copy pathnext_greater_node_in_ll.cpp
File metadata and controls
51 lines (42 loc) · 1.09 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Problem Link : https://leetcode.com/problems/next-greater-node-in-linked-list/description/
class Solution {
public:
ListNode *rev(ListNode *head){
if(head==NULL || head->next==NULL){
return head;
}
ListNode *prev = NULL ;
ListNode *curr = head ;
ListNode *nextNode =NULL ;
while(curr!=NULL){
nextNode = curr->next ;
curr->next = prev ;
prev = curr ;
curr = nextNode;
}
return prev ;
}
vector<int> nextLargerNodes(ListNode* head) {
vector<int>ans ;
head = rev(head) ;
if(head==NULL){
return ans ;
}
ListNode *curr = head ;
stack<int>st ;
st.push(curr->val) ;
ans.push_back(0) ;
curr= curr->next ;
while(curr!=NULL){
while(!st.empty() && st.top()<=curr->val){
st.pop() ;
}
int ng = st.empty()?0:st.top() ;
ans.push_back(ng) ;
st.push(curr->val) ;
curr=curr->next ;
}
reverse(ans.begin() , ans.end()) ;
return ans ;
}
};