[栈] leetcode 1019 Next Greater Node In Linked List

Posted fish1996

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[栈] leetcode 1019 Next Greater Node In Linked List相关的知识,希望对你有一定的参考价值。

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

        维护递减的单调栈。这道题对象是链表,不像数组可以快速通过下标索引,所以比较方便的做法是在栈中同时记录数字和对应的下标,并且默认填0,如果找到了比它大的第一个数,再修改下标对应的数字。

/**
 * Definition for singly-linked list.
 * struct ListNode 
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) 
 * ;
 */
class Solution 
public:
    vector<int> nextLargerNodes(ListNode* head) 
        stack<pair<int,int>> sta;
        vector<int> res;
        int i = 0;
        ListNode* cur = head;
        while(cur)
        
            while(!sta.empty() && cur->val > sta.top().first)
            
                int idx = sta.top().second;
                sta.pop();
                res[idx] = cur->val;
            
            sta.push( cur->val, i++);
            res.push_back(0);
            cur = cur->next;
        
        
        return res;
    
;

 

以上是关于[栈] leetcode 1019 Next Greater Node In Linked List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1019. Next Greater Node In Linked List

leetcode1019 Next Greater Node In Linked List

Leetcode 1019. Next Greater Node In Linked List

[LeetCode] 1019. Next Greater Node In Linked List

LeetCode 1019. Next Greater Node In Linked List (链表中的下一个更大节点)

[栈] leetcode 503 Next Greater Element II