Java删除链表的倒数第N个结点

本文介绍如何解决删除链表中倒数第N个节点的问题,提供了三种解题思路:计算链表长度、使用栈的先进后出特性和通过快慢指针同步移动来定位目标节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

19. 删除链表的倒数第N个结点
在这里插入图片描述在这里插入图片描述

解题思路1:
链表的长度len
删除链表的倒数第N个结点就是删除链表的第len - N个结点

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode tmp = new ListNode(0, head);
        int len = 0;
        while(tmp.next != null){
            len++;
            tmp = tmp.next;
        }
        ListNode node = new ListNode(0, head);
        int count = 1;
        while(true){
            if(n == len){
                node.next = head.next;
                break;
            }else if(count == len - n){
                head.next = head.next.next;
                break;
            }
            head = head.next;
            count++;
        }
        return node.next;
    }
}

解题思路2:
利用栈先进后出

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        Deque<ListNode> stack = new LinkedList<>();
        ListNode cur = dummy;
        while(cur != null){
            stack.push(cur);
            cur = cur.next;
        }
        for(int i = 0; i < n; i++){
            stack.pop();
        }
        ListNode pre = stack.peek();
        pre.next = pre.next.next;
        return dummy.next;
    }
}

解题思路3:
快慢指针
让快指针先走n

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head, slow = head;
        for(int i = 0; i < n; i++){
            fast = fast.next;
        }
        //如果fast == null, 说明fast走n步走到了最后
        //说明要删除的是头结点
        if(fast == null){
            return head.next;
        }
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值