tips:我深刻认识到了自己的菜鸡属性,单调栈的概念只会生用,稍微一变就怎么也出不来。
由于链表中存在重复的元素,正向使用单调栈会出现顺序上的错误,也不能简单使用hashmap,冥思苦想了一番之后还是选择了题解。。原来倒着做这么容易。。
一、pair<val,index>法,有这个思路
1 vector<int> nextLargerNodes(ListNode* head) { 2 ListNode* temp = head; 3 vector<int> res; 4 pair<int, int> map; //first:val second:下标 5 stack<pair<int,int>> use; 6 int count = 0; 7 while (temp != nullptr) 8 { 9 res.push_back(0); 10 while (!use.empty() && temp->val > use.top().first) 11 { 12 res[use.top().second] = temp->val; 13 use.pop(); 14 } 15 use.push(make_pair(temp->val, count++)); 16 temp = temp->next; 17 } 18 return res; 19 }
二、倒着用单调栈,先翻转链表,我是hamburger
1 vector<int> nextLargerNodes(ListNode* head) { 2 ListNode* dummy = nullptr; 3 ListNode* next = nullptr; 4 ListNode* temp = head; 5 while (temp != nullptr) 6 { 7 next = temp->next; 8 temp->next = dummy; 9 dummy = temp; 10 temp = next; 11 } 12 temp = dummy; 13 14 stack<int> use; 15 stack<int> res; 16 while (temp != nullptr) 17 { 18 if (use.empty()) 19 { 20 use.push(temp->val); 21 res.push(0); 22 } 23 else if (!use.empty() && temp->val < use.top()) 24 { 25 res.push(use.top()); 26 use.push(temp->val); 27 } 28 else 29 { 30 while (!use.empty() && temp->val >= use.top()) 31 { 32 use.pop(); 33 } 34 if (use.empty()) 35 res.push(0); 36 else 37 res.push(use.top()); 38 use.push(temp->val); 39 } 40 temp = temp->next; 41 } 42 vector<int> result; 43 while (!res.empty()) 44 { 45 result.push_back(res.top()); 46 res.pop(); 47 } 48 return result; 49 }