zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    PHP实现畅言留言板和网易跟帖样式
    关于MySql中自增长id设置初始值
    建议
    P3P解决cookie存取的跨域问题
    学习模板实例
    Mac 安装Bower
    webstorm for mac 破解步骤
    Mac上搭建php开发环境
    ios 开发之 -- 极光推送,发送自定义消息,进入制定页面
    ios开发之 -- 强制横屏
  • 原文地址:https://www.cnblogs.com/LiuQiujie/p/12678072.html
Copyright © 2011-2022 走看看