Leetcode -19. Remove Nth Node From End of List 题解

本文介绍了一种高效算法,用于从链表中删除倒数第N个节点。通过使用双指针技巧,可以在一次遍历中完成任务。文章提供了详细的实现思路和Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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?

思路:

使用两个temp指针变量,第一个指针变量指向列表正数第N个元素,第二个指向列表第一个元素,在第一个指针变量的下一个元素不为空时这两个变量同时指向下一个元素,当第一个指针变量指向最后一个元素时,第二个变量指向的就是列表倒数第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, n):
		if head == None or head.next == None:
			return None
		temp1 = head
		temp2 = head
		for i in range(n):
			temp1 = temp1.next
		if temp1 == None:  # 删除倒数最后一个也就是第一个元素
			return head.next
		while temp1.next:
			temp1 = temp1.next
			temp2 = temp2.next
		temp2.next = temp2.next.next
		return head

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值