Remove Duplicates from Sorted List

題目
思路:

  1. 既然是 Linked List,我們可以宣告一個指標 curr 指向第一個 node,用 while 迴圈一次檢查一個 node (檢查完將指標移到下一個 node)

    • 不能直接用 head 來移動,因為到時候回傳答案的時候需要回傳這個 head
  2. 設定 while 可以繼續檢查的條件:有時要先寫 while 的內容,才會比較確定 while 條件應該怎麼寫,這時可以先寫 while True:,等內容寫完再來改條件

  3. 寫 while 內容

    1. 假如 curr.val 跟下一個一樣,就把 next 接到下下個

      1
      2
      if curr.val == curr.next.val:
      curr.next = curr.next.next
    2. 但假如下下個也一樣呢?=> 把上面的 if 改成 while,讓最後 curr.next 所指的 val 一定是不一樣的

    3. 改成 while 之後,檢查條件會被重複執行。因為 curr.next 有可能會是 None,所以條件改為
      while curr.val == (curr.next and curr.next.val):

    4. 離開 while 之後:
      curr = curr.next # 把指標移到下一個 node,以便下次的檢查

  4. 回去修改 while 條件:什麼條件成立我們才能繼續檢查(執行 while 內容)?

    1. 首先 curr 不能是 None
      • curr 有可能是 None,因為我們一直把它指向下一個 Node,到了盡頭 curr 就會是 None
    2. 即使 curr.nextNone,還是可以順利執行迴圈內容
    3. 結論:條件為 while curr:
  5. 離開 while 之後就大功告成,回傳答案 head

Python3 solution:

1
2
3
4
5
6
7
8
9
10
11
12
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
curr = head # 等一下可以在 while 迴圈中移動的指標
while curr:
while curr.val == (curr.next and curr.next.val):
curr.next = curr.next.next
curr = curr.next
return head

評論

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×