leetcode #19

该博客介绍了LeetCode中的问题#19,即如何在一次遍历中从链表末尾移除第n个节点。通过使用两个指针pre和cur,初始指向链表头。cur先向前移动n步,如果cur为空,说明n等于链表长度,需删除头节点;否则,cur继续前进,pre也跟随移动,当cur为空时,删除pre的下一个节点。

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

==============================================================================

【id】#19

【title】Remove Nth Node From End of List

【description】

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

【idea】

要求是遍历一遍就要解决问题。首先要找到倒数第n个节点,利用两个指针pre和cur,初始化都在head。cur向前移动n步,如果此时cur为空指针,说明n为链表长度,也就是删除头节点,返回head.next。
如果cur存在,那么cur继续向前一定,pre也向前移动,当cur为空时,说明要删除pre的下一个节点。

画图体会一下更容易理解。

【code】

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        pre = cur = head
        for _ in  range(n):
            cur = cur.next
        if not cur : return head.next
        while cur.next:
            cur = cur.next
            pre = pre.next
        pre.next = pre.next.next
        return head

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值