LeetCode 2487. 从链表中移除节点:单调栈

【LetMeFly】2487.从链表中移除节点:单调栈

力扣题目链接:https://leetcode.cn/problems/remove-nodes-from-linked-list/

给你一个链表的头节点 head

移除每个右侧有一个更大数值的节点。

返回修改后链表的头节点head

示例 1:

复制代码
输入:head = [5,2,13,3,8]
输出:[13,8]
解释:需要移除的节点是 5 ,2 和 3 。
- 节点 13 在节点 5 右侧。
- 节点 13 在节点 2 右侧。
- 节点 8 在节点 3 右侧。

示例 2:

复制代码
输入:head = [1,1,1,1]
输出:[1,1,1,1]
解释:每个节点的值都是 1 ,所以没有需要移除的节点。

提示:

  • 给定列表中的节点数目在范围 [1, 105]
  • 1 <= Node.val <= 105

方法一:单调栈

维护一个单调递减栈(严格地说是单调非递增栈):

遍历链表,在当前节点大于栈顶节点时不断弹出栈顶节点,然后将当前节点入栈。

最终,从栈底到栈顶的元素就是非递增的了。因此也就得到了想要的链表。

  • 时间复杂度 O ( l e n ( l i s t n o d e ) ) O(len(listnode)) O(len(listnode))
  • 空间复杂度 O ( l e n ( l i s t n o d e ) ) O(len(listnode)) O(len(listnode))

然后被丢弃节点的delete操作就靠力扣了hh。

AC代码

C++
cpp 复制代码
class Solution {
public:
    ListNode* removeNodes(ListNode* head) {
        stack<ListNode*> st;
        while (head) {
            while (st.size() && st.top()->val < head->val) {
                st.pop();
            }
            st.push(head);
            head = head->next;
        }
        ListNode* lastNode = nullptr;
        while (st.size()) {
            ListNode* thisNode = st.top();
            st.pop();
            thisNode->next = lastNode;
            lastNode = thisNode;
        }
        return lastNode;
    }
};
Python
python 复制代码
class Solution:
    def removeNodes(self, head: ListNode) -> ListNode:
        st = []
        while head:
            while len(st) and st[-1].val < head.val:
                st.pop()
            st.append(head)
            head = head.next
        for i in range(len(st) - 1):
            st[i].next = st[i + 1]
        return st[0]

同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/135357617

相关推荐
宝贝儿好2 小时前
【强化学习实战】第十一章:Gymnasium库的介绍和使用(1)、出租车游戏代码详解(Sarsa & Q learning)
人工智能·python·深度学习·算法·游戏·机器学习
weixin_458872615 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll5 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人5 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn5 小时前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答6 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂6 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
Neteen6 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
礼拜天没时间.6 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区6 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展