我的方法是用一個隊列,保存後N個節點,但是內存消耗比較大,方法如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
stackList = []
from collections import deque
stackList = deque(stackList)
p = head
while p is not None:
if len(stackList) <= n:
stackList.append(p)
else:
stackList.popleft()
stackList.append(p)
p = p.next
if len(stackList) == n: #這裏是爲了應對出現stackList不滿(即不是n+1)的情況
stackList.popleft()
try:
return stackList[0]
except:
return None
stackList[0].next = stackList[1].next
return head
還用一種雙指針方法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
headNode = ListNode(-1) #在head之前增加節點可以避免出現listNode長度和n一致的情況
headNode.next = head
front = headNode
end = front
for _ in range(n): #排頭指針先跑n步,保證和隊尾指針相差n,即隊尾指針的next是要刪除的
front = front.next
while front.next is not None:
front = front.next
end = end.next
end.next = end.next.next
return headNode.next