力扣 1019. 链表中的下一个更大节点(单调栈)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector nextLargerNodes(ListNode* head) {
        
        vector v,res;
        if(head==NULL)
            return v;
        while(head!=NULL)
        {
            v.push_back(head->val);
            res.push_back(0);
            head=head->next;
        }
        int len=v.size();
        stack st;

        for(int i=len-1;i>=0;i--)
        {
            while(!st.empty()&&st.top()<=v[i])
                st.pop();
            if(st.empty())
                res[i]=0;
            else
                res[i]=st.top();
            st.push(v[i]);
        }
        return res;
    }
};

 

你可能感兴趣的:(题目)