python【力扣LeetCode算法题库】19-删除链表的倒数第N个节点

Jennifer ·
更新时间:2024-09-21
· 868 次阅读

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

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 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: global count if head is None: count=0 return None #从递归出口一层一层往回 head.next=self.removeNthFromEnd(head.next,n) count+=1 if n==count: return head.next # 跳过n结点 else: return head

在这里插入图片描述


作者:Li xiang007



题库 leetcode 链表 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号