19. 删除链表的倒数第N个节点

题目描述

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

一遍过法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        pre_head=ListNode(1)
        pre_head.next=head
        a=b=pre_head #a对应倒数第n+1个节点,b对应最后一个节点
        if head.next==None:
            return None
        while n>0:
            b=b.next
            n-=1
        while b.next:
            a=a.next
            b=b.next
        a.next=a.next.next
        return pre_head.next

相当于a和b保持n个距离然后同时前进,当b为最后一个元素时,把a后面的元素删去

执行用时 :32 ms, 在所有 Python3 提交中击败了88.03%的用户
内存消耗 :13.5 MB, 在所有 Python3 提交中击败了7.83%的用户

两遍过法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        pre_head=ListNode(1)
        pre_head.next=head
        a=b=pre_head #a对应倒数第n+1个节点,b对应最后一个节点
        w=0 #n是计数器
        while b.next:
            w+=1
            b=b.next
        while w-n>0:
            w-=1
            a=a.next
        a.next=a.next.next
        return pre_head.next

b先遍历数组,用w来记录有几个元素,这样就知道应该删除第几个元素了,然后a再往后走直到走到相对应的位置进行删除

执行用时 :40 ms, 在所有 Python3 提交中击败了47.91%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了7.52%的用户

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值