網(wǎng)站開發(fā)畢設(shè)文獻(xiàn)網(wǎng)絡(luò)營(yíng)銷swot分析
2487. 從鏈表中移除節(jié)點(diǎn)
給你一個(gè)鏈表的頭節(jié)點(diǎn) head 。
移除每個(gè)右側(cè)有一個(gè)更大數(shù)值的節(jié)點(diǎn)。
返回修改后鏈表的頭節(jié)點(diǎn) head 。
示例 1:
輸入:head = [5,2,13,3,8]
輸出:[13,8]
解釋:需要移除的節(jié)點(diǎn)是 5 ,2 和 3 。
- 節(jié)點(diǎn) 13 在節(jié)點(diǎn) 5 右側(cè)。
- 節(jié)點(diǎn) 13 在節(jié)點(diǎn) 2 右側(cè)。
- 節(jié)點(diǎn) 8 在節(jié)點(diǎn) 3 右側(cè)。
示例 2:
輸入:head = [1,1,1,1]
輸出:[1,1,1,1]
解釋:每個(gè)節(jié)點(diǎn)的值都是 1 ,所以沒有需要移除的節(jié)點(diǎn)。
提示:
給定列表中的節(jié)點(diǎn)數(shù)目在范圍 [1, 105] 內(nèi)
1 <= Node.val <= 1e5
既然題目要倒著看最大值,明顯可以用到遞歸,利用遞歸確定每個(gè)數(shù)右側(cè)都是比他大的:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* removeNodes(ListNode* head) {if(head -> next == nullptr) {return head;}ListNode* node = removeNodes(head -> next);if(node -> val > head -> val) {return node;}head -> next = node;return head;}
};
看完題解后還有另外的解法,也就是單調(diào)棧:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* removeNodes(ListNode* head) {ListNode* dummy = new ListNode(0, head);ListNode* cur = head;vector<ListNode*> stk;for (ListNode* cur = head; cur; cur = cur->next) {while (stk.size() && stk.back()->val < cur->val) {stk.pop_back();}if (stk.size()) {stk.back()->next = cur;} else {dummy->next = cur;}stk.push_back(cur);}return dummy->next;}
};
靈神題解中還用了迭代來做:
class Solution {ListNode *reverseList(ListNode *head) {ListNode *pre = nullptr, *cur = head;while (cur) {ListNode *nxt = cur->next;cur->next = pre;pre = cur;cur = nxt;}return pre;}
public:ListNode *removeNodes(ListNode *head) {head = reverseList(head);ListNode *cur = head;while (cur->next) {if (cur->val > cur->next->val) {cur->next = cur->next->next;} else {cur = cur->next;}}return reverseList(head);}
};