这个问题其实是比较简单的,我的思路是,把最后N+1个节点保存下来,链表遍历完之后,直接操作之前保存节点的最早一个即可。PS:经试验,python里面的List结构,存是的指针,而不是COPY,所以可以直接对list进行操作来改变原始数据。
我的代码:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
buf = []
cur = head
i = 0
while cur.next != None:
if i < n:
buf.append(cur)
else:
buf[i%n] = cur
cur = cur.next
i += 1 #i is the number of nodes - 1
if i == 0:
return None
if n == 1:
buf[i % n].next = None
elif n == 2:
if i == 1:
head = cur
else:
buf[i % n].next = cur
elif n == i + 1:
head = buf[1]
else:
buf[i%n].next = buf[(i+2)%n]
return head
效率在结果里面占了中位数,后来看到某大神的答案,代码更为简洁,使用了fast和slow两个指针来遍历链表,fast和slow中间相隔N,fast遍历完之后,slow的位置就是要操作的位置了,对大神代码进行优化后,代码:
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
fast, slow = head, head
for _ in range(n):
fast = fast.next
if fast is None:
return slow.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
Good Luck, and have a nice day!