题目描述:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
方法一:双指针
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
"""
node=ListNode(-1)#新建一个链点
node.next=head#把新建的链点放到开头
first=second=node #建立两个指针
for i in range(n):
first=first.next #让first前进n个单位
while first.next: #只要first的后一个不为空
#first和second同时后移,通过间隔n来解决获得倒数第n的问题
first=first.next
second=second.next
second.next=second.next.next#一个掐断链点的模板 左边比右边少一个next
return node.next
#到此为主,我们终于了解了这个node的作用
# 1)用来返回,
# 2)通过在前面设定一个node,避免后面搞什么n-1之类的循环
这个方法的使用一个哑节点来保持距离。
双指针不仅在数组中使用,在链表中使用双指针也是常识
总结一下在链表中双指针的用法
1)用于追踪节点和替换节点关系
2)用于锁定具有一定距离关系的节点
方法二:递归
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
global count
if head is None:
count=0 #在none的时候记0,因为没有倒数第0
return None
head.next=self.removeNthFromEnd(head.next,n)
#当count==n时,此句等效于head.next=head.next.next
count+=1
return head.next if n==count else head #这里的判读,决定返回的出口
有一段话说得很好
递归其实是两个过程,递和归!
这种解法用一句话形容,就是在递和归重合得时候,把需要去掉得节点去除。
在递归中使用global,否则不能击穿递归块。
怎么理解递归?
我觉得用嵌套的正方形模块进行理解比较好。
还是自己体会吧~
收获与思考
自己看代码,收获都在代码注释和下面得解释中