Leetcode 19.删除链表的倒数第 N 个结点 Remove Nth Node From End of List - Python 双指针法Vs笨蛋法

笨蛋法

# 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: ListNode, n: int) :
        size = 1
        count = head
        while count.next!=None:
            size +=1
            count = count.next    #先计算一下数组长度
        cur = head
           #这里要根据size的大小分情况
        if size >1:
            if size == n:
                head = head.next
                return head
            else:
                for _ in range(size-n-1):
                    cur = cur.next
                cur.next = cur.next.next
                return head
        else:
            head = None
            return head

快慢指针法(双指针法)

# 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: ListNode, n: int) -> ListNode:
        sentinalNode = ListNode(next=head)
        slow, fast = sentinalNode, sentinalNode

#快指针先走n+1的原理是:此时slow在哨兵节点,fast在把n倒数看为正数的先驱节点
#即此时slow与fast的相对位置 与fast最终指向NULL时,slow指向倒数待删除节点的先驱节点时它俩的相对位置
#成镜像对称,fast指向NULL时, 此时的fast就是一开始的slow,此时的slow就是一开始的fast

        for _ in range(n+1):  
            fast = fast.next
        
        while fast != None:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next

        return sentinalNode.next

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值