删除链表的倒数第N个结点,并返回链表的头结点python3

Leetcode 19题 力扣

个人主要从删除头结点,尾结点,和中间结点三种情况进行处理,考虑这三种情况的删除方法

完整程序

"""
力扣题 :19 删除链表的倒数第N个结点

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
2022.5.6
解题思路:
主要考察删除结点的位置 :头结点,尾结点,中间节点

"""


class ListNode:
    def __init__(self,val = 0 ,next = None):
        self.val = val
        self.next = next

class Solution:
    def removeNthFromEnd(self,head,n):
        if not head:
            return head

        cur = head
        cur2 = head
        count = 0
        # 计算链表长度
        while cur:
            count += 1
            cur = cur.next

        tar_n = count - n + 1 # 要删除的节点是第tar_n个结点

        # 删除链表头部结点
        if tar_n == 1:
            if cur2.next == None:
                head = None
            else:
                head = head.next
        elif tar_n == count: # 删除链表尾结点
            while cur2.next:
                tar_n -= 1
                if tar_n == 1:
                    cur2.next = None
                else:
                    cur2 = cur2.next

        else:# 删除链表中间的结点
            while cur2.next:
                tar_n -= 1
                if tar_n == 1:
                    cur2.next = cur2.next.next
                else:
                    cur2 = cur2.next

        return head




arr = [1,2]
n = 2
head = ListNode(0)
cur = head
for i in range(len(arr)):

    node = ListNode(arr[i])
    cur.next = node
    cur = cur.next

l2 = Solution().removeNthFromEnd(head.next,n)
while l2:
    print(l2.val,end='')
    l2 = l2.next



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值