如何用Python实现删除链表倒数第N个节点的力扣问题?

2026-06-11 08:451阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计392个文字,预计阅读时间需要2分钟。

如何用Python实现删除链表倒数第N个节点的力扣问题?

题目描述:中文给定一个链表,删除链表的倒数第n个节点,并返回链表的头节点。

如何用Python实现删除链表倒数第N个节点的力扣问题?

示例:给定一个链表:1-2-3-4-5,和n=2。当删除了倒数第二个节点后,链表变为:1-2-3-5。

说明:

题目描述:

中文:

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

示例:

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

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

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

英文:

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ dummy = ListNode(0) dummy.next = head p1=p2=dummy for i in range(n): p1 = p1.next while p1.next: p1=p1.next p2=p2.next p2.next = p2.next.next return dummy.next

题目来源:力扣

本文共计392个文字,预计阅读时间需要2分钟。

如何用Python实现删除链表倒数第N个节点的力扣问题?

题目描述:中文给定一个链表,删除链表的倒数第n个节点,并返回链表的头节点。

如何用Python实现删除链表倒数第N个节点的力扣问题?

示例:给定一个链表:1-2-3-4-5,和n=2。当删除了倒数第二个节点后,链表变为:1-2-3-5。

说明:

题目描述:

中文:

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

示例:

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

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

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

英文:

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ dummy = ListNode(0) dummy.next = head p1=p2=dummy for i in range(n): p1 = p1.next while p1.next: p1=p1.next p2=p2.next p2.next = p2.next.next return dummy.next

题目来源:力扣