代码思路:采用双指针,快指针先走n次,接下来快慢指针同时走,直到快指针走完时,慢指针所在位置即为需要删除的节点
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow=head
fast=head
while n>0:
fast=fast.next
n-=1
if fast:
while fast.next:
fast=fast.next
slow=slow.next
slow.next=slow.next.next
return head
else:
return head.next