leetcode 1019 Next Greater Node In Linked List

1. 按序放入栈中,如果当前数字比栈中的数字大,则出栈,更新这个数的next greater node。

class Solution {
public:
    vector<int> nextLargerNodes(ListNode* head) {
        vector<int> vec;
        stack<pair<int,int>> s;
        ListNode *node=head;int i=0;
        while(node) {
            vec.push_back(0);
            while(!s.empty()&&s.top().second<node->val) {
                auto a=s.top();s.pop();
                vec[a.first]=node->val;
            }
            s.push({i,node->val});
            node=node->next;
            ++i;
        }//while
        return vec;
    }
};

2. 翻转链表,遍历链表;将栈中比当前数小的都pop出来,如果栈空,说明后面没有比它大的,如果栈不空,栈顶元素就是next greater node。栈顶元素是当前遍历到的最大的元素。

class Solution {
public:
    vector<int> nextLargerNodes(ListNode* head) {
        vector<int> vec;
        stack<int> s;
        head=reverse(head);
        while(head) {
            while(!s.empty()&&s.top()<=head->val) s.pop();
            if(s.empty()) vec.push_back(0);
            else vec.push_back(s.top());
            s.push(head->val);
            head=head->next;
        }
        std::reverse(vec.begin(),vec.end());
        return vec;
    }
    ListNode* reverse(ListNode* head) {
        ListNode* pre=nullptr,*cur=head,*next=head;
        while(cur) {
            next=cur->next;
            cur->next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
};
原文地址:https://www.cnblogs.com/LiuQiujie/p/12678072.html