36 ms 14.8 MB Python3
# 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:
i=1
p=pre=q=head
while i<n and q.next!=None:
q=q.next
i+=1
while q.next!=None:
pre=p
p=p.next
q=q.next
if pre==p:
head=head.next#解决删除唯一元素的情况
else:
pre.next=p.next#不能解决[1] 1的情况
return head