1.代码
# 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: Optional[ListNode], n: int) -> Optional[ListNode]:
now = head
tail = head
for i in range(n):
tail = tail.next
if tail:
while tail.next:
now = now.next
tail = tail.next
now.next = now.next.next
else:
head = head.next
return head
2.思路
一开始now和tail都指向head,然后把tail向后移动n次,这样当tail指向链表末尾时,head指向倒数第n个结点的前一个,可以方便地删除倒数第n个结点。