题目
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
解法分析
使用快慢指针法,先让快指针走n+1
步,然后快慢指针同时走,当快指针走到链表结尾时慢指针走到倒数第n
个节点的前一个节点,方便操作。
Python写法
# 创建一个单向链表
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head = ListNode(next=head)
slow = dummy_head
fast = dummy_head
# for i in range(i + 1):
# fast = fast.next
while n+1 and fast:
n -= 1
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next