没有指针,如何指示head.next * n好痛苦,最后想了半天用了list来存储每一级的next来解决。代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
c = head
a = []
while True:
if head != None:
a.append(head.val)
head = head.next
else:
break
b = []
if len(a) - n == 0:
return c.next
if len(a) - n < 0:
return c
for i in range(len(a) - n):
if b == []:
b.append(c)
else:
b.append(b[-1].next)
b[-1].next = b[-1].next.next
return c