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; } };
原文地址:https://www.cnblogs.com/fish1996/p/11335303.html
时间: 2024-10-30 12:39:13