※ 引述《Rushia (みけねこ的鼻屎)》之銘言:
: 19. Remove Nth Node From End of List
: 移除鏈結串列後面數來的第n個節點,題目保證n必定小於串列長度。
: 思路:
: 1.用快慢指針來求解
: 2.先讓快指針走n步,再來快慢指針一起走直到快指針為null
: 3.慢指針最後會停在要被刪除的元素之前,將他指向下下個元素
: 4.避免遇到要刪除的節點是頭節點,我們用一個dummy作為頭節點,快指針也改
: 成多走一步。
: 5.返回dummy.next
Python code:
class Solution(object):
def removeNthFromEnd(self, head, n):
prev = ListNode()
prev.next = head
curr = prev
dele = prev
for i in range(n):
curr = curr.next
while curr.next != None:
curr = curr.next
dele = dele.next
dele.next = dele.next.next
return prev.next
兩年前的code 認不出來是我寫的==
中間可以多加個判斷
如果移完 fast 發現 fast == Null 就代表要刪掉的是 head
這時候直接回傳 head.next 就可以 這樣就不用 dummy head 了
像這樣
class Solution(object):
def removeNthFromEnd(self, head, n):
fast = slow = head
for i in range(n):
fast = fast.next
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
應該有比較漂亮