# 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:
first = head
list_length = 1
while first.next != None:
list_length += 1
first = first.next
# 特殊处理n=list_length的情况,此时删除的是头结点
if n == list_length:
head_next = head.next
head.next = None
return head_next
second = head
nth_count = 1
while nth_count < list_length - n + 1:
if nth_count == list_length - n:
node_after_nth = second.next.next
second.next.next = None
second.next = node_after_nth
break
nth_count += 1
second = second.next
return head