'''
解题思路:
1、将链表节点加入一个List型数组 arr, 通过操作arr[i].next来实现删除
2、head实际长度可能为 0,1,2,3……,head值尽量不要动,其它操作用副本t=head
3、删除的位置在中间是正常情况,异常情况要考虑头尾,超范围等
'''
# 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 , n ):
        # write code here
        if not head:
            return None

        t = head
        arr = []
        while t:
            arr.append(t)
            t = t.next
        m = len(arr)

        if m==1:
            if n==1:
                return None
            else:
                return head

        if n==1:
            arr[-2].next = None
            head = arr[0]
        elif n==m:
            head = arr[1]
        elif 1<=n-1<=m and 1<=n+1<=m:
            arr[-(n+1)].next = arr[-(n-1)]
        return head

'''
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head = Solution().removeNthFromEnd(head,3)

while head:
    print(head.val, end=' ')
    head = head.next
'''