题目说明
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
解题思路
- 遍历链表A到尾部,并计算count;然后遍历链表B判断count>n,跳出循环则head.next=head.next.next。
- 遍历链表A count与n的距离,然后接着遍历链表A,链表B,跳出循环则head.next = head.nexe.next
代码如下
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# 通过链表移动计算出链表大小与删除节点位置的距离
res = ListNode(next=head) # 创建一个虚拟节点,next指向头
h_head = l_head = res
count = 0
while l_head.next is not None and count != n: # 移动尾节点,使其与头节点保持n个节点
l_head = l_head.next
count += 1
while l_head.next is not None: # 尾节点遍历完
l_head = l_head.next
h_head = h_head.next
h_head.next = h_head.next.next # 头节点的下一个节点指向它的下下个节点
return res.next
def removeNthFromEnd_1(self, head: ListNode, n: int) -> ListNode:
# 先遍历链表长度,然后判断长度与删除节点的距离
res = ListNode(next=head) # 创建一个虚拟节点,next指向头
h_head = l_head = res
count = 0
while l_head.next is not None: # 第一位是虚拟的头节点
l_head = l_head.next
count += 1
while count > n:
h_head = h_head.next
count -= 1
h_head.next = h_head.next.next # 头节点的下一个节点指向它的下下个节点
return res.next