【力扣100】19.删除链表的倒数第N个节点

添加链接描述

# 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]:
        # 思路是先统计总个数,然后循环找到节点前一个,更改next
        count=0
        copy_head=head
        ans_head=head
        while head:
            count=count+1
            head=head.next
        if count==n:
            return ans_head.next
        for i in range(count-n-1):
            copy_head=copy_head.next
        copy_head.next=copy_head.next.next if copy_head.next.next else None
        return ans_head

思路是:

  1. 首先统计一下整个链表长多少
  2. 然后使用for循环到要删除的前一个节点,next操作
  3. 同时这里要注意踢出一个条件,就是当要删除第一个节点时,直接返回第二个节点。


双指针解法

思路:

  1. pre节点指向head的前一个节点
  2. slow 赋值为pre,fast 赋值为head
  3. 先让fast走n步
  4. 然后,fast slow 一起走,直到while fast,这时候slow 到要删除的节点的前一个节点
  5. 然后next操作
# 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]:
        #10:45
        '''
        Two pointer
        '''
        #this is needed bcuz what if first Node need to be removed
        dummyHead = ListNode(0, head)
        slow, fast = dummyHead, head
        i = 0
        while i != n:
            i += 1
            fast = fast.next

        while fast != None:
            slow = slow.next
            fast = fast.next

        slow.next = slow.next.next

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值