1 问题
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
2 答案
这题直接不会
循环迭代
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
#step1: 获取链表长度
cur, length = head, 0
while cur:
length += 1
cur = cur.next
#step2: 找到倒数第N个节点的前面一个节点
cur = dummy # cur 修改时 dummy 也会跟着一起修改,但next操作不会
for _ in range(length - n):
cur = cur.next
#step3: 删除节点,并重新连接
cur.next = cur.next.next
return dummy.next