LeetCode刷题笔记第19题:删除链表的倒数第 N 个结点
想法:
要想删除链表中倒数第N个结点,首先要找到此结点,通过链表删除结点的操作删除结点。设置两个指针,第一个指针找到第N个结点的位置,第二个结点在初始位置,然后将两个指针同时向后移动,当第一个指针遍历链表结束时,第二个指针刚好移动到倒数第N个结点。
# 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:
dummy = ListNode(0, head)
first = head
second = dummy
# 用first找到第N个结点
for i in range(n):
first = first.next
# 两个指针同时移动
while first:
first = first.next
second = second.next
# 删除倒数第N个结点
second.next = second.next.next
return dummy.next