【力扣每日一题】力扣2478从链表中移除节点

文章介绍了如何使用栈数据结构解决链表问题,即从给定链表中移除右侧数值大于当前节点的元素,提供了Java和C++两种实现方法。
摘要由CSDN通过智能技术生成

题目来源

2478.从链表中移除节点

题目描述

给你一个链表的头节点 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, 10^5] 内
  • 1 <= Node.val <= 100000

解题思路

使用栈来解决这个问题

  1. 若栈为空,元素入栈;
  2. 若栈不为空,且栈顶元素不小于当前元素,元素入栈;
  3. 若栈不为空,且栈顶元素小于当前元素,进行出栈操作,直到栈空或者栈顶元素不小于当前元素,元素入栈。

代码

java代码使用双链表模拟栈

public class Solution {
    public ListNode removeNodes(ListNode head) {

        DoubleLink dhead = new DoubleLink();  // 栈底
        DoubleLink trail = dhead;             // 栈顶
        dhead.val = head;                     // 第一个元素入栈
        ListNode current = head.next;         // 当前元素
        while (current != null) {
            if (current.val > trail.val.val) { // 如果当前元素大于已经入栈的元素,出栈到栈顶元素大于当前元素
                while (trail != null && trail.val.val < current.val){
                    trail = trail.pre;
                }
            }
            if (trail == null) {                // 如果变为空栈,直接入栈
                dhead.val = current;
                dhead.pre = null;
                trail = dhead;
            }else {                             // 将元素入栈,并且连接指针
                trail.next = new DoubleLink();
                trail.next.pre = trail;
                trail = trail.next;
                trail.val = current;
                trail.pre.val.next = current;
            }
            current = current.next;
        }
        return dhead.val;
    }
}
// 题目指定的链表结构
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
// 用来模拟栈的双链表
class DoubleLink{
    public DoubleLink pre;// 前驱
    public ListNode val; // 内容
    public DoubleLink next; // 后继
}

c++代码使用数组模拟栈

class Solution {
public:
    ListNode* removeNodes(ListNode* head) {
        ListNode** nodeArray = new ListNode*[10000];
        nodeArray[0] = head;
        int index = 0;
        ListNode* current = head->next;
        while (current != nullptr) {
            if (current->val > nodeArray[index]->val) {
                while (index >= 0 && nodeArray[index]->val < current->val) {
                    index--;
                }
            }
            nodeArray[++index] = current;
            if (index > 0) {
                nodeArray[index - 1]->next = current;
            }
            current = current->next;
        }
        return nodeArray[0];
    }
};

结果

java结果

c++结果

c++的大佬也太强了吧

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值