【重点】19.删除链表的倒数第N个结点

文章介绍了在链表操作中,如何使用头节点和不使用头节点的方法来删除给定位置的节点,通过快慢指针实现,包括法1(使用虚拟头结点)和法2(直接操作)。

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

题目

Python

参考:灵茶山艾府

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(-1)
        dummy.next = head
        slow = dummy # slow, fast初始位置都在虚拟头结点上
        fast = dummy
        for i in range(0, n):
            fast = fast.next
        while fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return dummy.next

Java

法1:使用头结点

注意使用虚拟头结点!!!

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode dummy = new ListNode(-1); // 虚拟头结点
        dummy.next = head;
        ListNode slow = dummy, fast = dummy;
        while (n > 0) {
            fast = fast.next;
            --n;
        }
        while (fast != null && fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}

法2:不使用头结点

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode fast = head, slow = head;
        while (n > 0 && fast != null) {
            fast = fast.next;
            --n;
        }
        if (fast == null) { // 删除正数第1个结点
            return head.next;
        }

        while (fast.next != null) { // fast停留在最后的结点上, slow停留在被删除的前一个结点上
            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、付费专栏及课程。

余额充值