1019链表中的下一个更大元素 Posted on 2020-04-19 Words count in article: 472 | Reading time ≈ 2 1019.链表中的下一个更大元素下面是题目下面是题目给出的模板1234567891011121314/** * 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) { }}; 这里用最普通的思路,和用栈模拟的方法 1234567891011121314151617181920212223242526//这个思路就时很简单,用两个迭代器,每次更新一个迭代器,都把他们后面的所有元素遍历一遍class Solution {public: vector<int> nextLargerNodes(ListNode* head) { ListNode*cur1 = head; vector<int>v; while(cur1->next) { ListNode *cur2 = cur1->next; while(cur2) { if(cur2->val>cur1->val) { v.push_back(cur2->val); break; } cur2=cur2->next; } if(!cur2) v.push_back(0); cur1 = cur1->next; } v.push_back(0); return v; }}; 用栈来做,思维要求比较高12345678910111213141516171819202122232425262728293031323334353637vector<int> nextLargerNodes(ListNode* head) { //将链表放入结果数组 vector<int> res; while (head) { res.push_back(head->val); head = head->next; } stack<int> stack; //从右往左遍历 for (int i = (int)res.size() - 1; i >= 0; --i) { int cur = res.at(i); //先暂存当前元素 while (!stack.empty() && cur >= stack.top()) //注意: 等于号不能少 等于时也需要出栈 这里是找严格大于的数 { stack.pop(); //淘汰小的 留下更大的 } res.at(i) = (stack.empty() ? 0 : stack.top()); //栈空 右边没有更大的 stack.push(cur); } return res; }}; //我们不妨拿一组数据来模拟一下 2 7 2 3 /*1: res[3]= 3 ,cur = 3 , stack 内的元素 :0 =>>>>> res[3]=0 stack 内的元素: 32: res[2]= 2 ,cur = 2 , stack 内的元素 :3 =>>>>> res[2]=3 stack 内的元素: 33: res[1]= 7 ,cur = 7 , stack 内的元素 :3 =>>>>> stack 出栈res[1]=0 stack 内的元素:74: res[0]= 2 ,cur = 2 , stack 内的元素 :7 =>>>>> res[0]=7 stack 内的元素: 7然后输出*/ -------------本文结束,感谢您的阅读------------- Post author: Jason Post link: https://jasonxqh.github.io/2020/04/19/1019%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E4%B8%8B%E4%B8%80%E4%B8%AA%E6%9B%B4%E5%A4%A7%E5%85%83%E7%B4%A0/ Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.