题目:
给你一个链表,删除链表的倒数第 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]
思路:
采用快慢指针,快指针先往后移动n个元素,而后慢指针和快指针一起移动,直到快指针到达最后一个元素,此时,慢指针正好指向要删除的前一个元素。通过指针的赋值操作,移除慢指针后的元素。
注意:删除第一个元素和最后一个元素时为特殊情况。在head指针前创一个空节点,指向头节点,避免删除第一个指针时出错。
代码:
# Definition for singly-linked list.
# 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:
cur = ListNode(None, head)
high = head
low = cur
for i in range(n):
high = high.next
while high:
low = low.next
high = high.next
low.next = low.next.next
return cur.next