# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param n int整型 
# @return ListNode类
#
class Solution:
    def removeNthFromEnd(self , head: ListNode, n: int) -> ListNode:
        # write code here
        cur = head
        post = head
        pre = None
        if not cur:
            return None
        length = 0
        while post:
            length += 1
            post = post.next
        a = length - n #计算倒数第n个节点前面有几个节点数
        if a == 0: #如果长度和n相同,直接返回第二个节点起的子链表
            return cur.next
        i = 0
        while cur:#从头节点开始,移动a-1次指针,将当前指针cur的next节点删掉即可。具体操作是,将当前指针cur赋值给pre,然后将pre的next指向cur的next的next
            if a == i + 1:
                pre = cur
                pre.next = cur.next.next
                return head
            i = i + 1
            cur = cur.next