# 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
#防止head为空
if head is None or n ==0:
return head
#链表只有一个节点的情况
if head.next is None :
if n == 1:
return None
if n==0:
return head
#保存链表头
head_r = head
#计算列表长度
l = 0
while head:
l+=1
head = head.next
#重新开始遍历
head = head_r
#找到倒数n+1个节点,并删除它的下一个节点
if l==n:
return head_r.next
for i in range(l-n-1):
head = head.next
head.next = head.next.next
return head_r