1.學習鏈表
鏈表只需定義head, head指向鏈表的頭部node,剩餘部分都由node完成
node 包含兩個屬性, value和next
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
class UnorderedList:
def __init__(self):
self.head = None
2. 讀題
刪除鏈表的指定元素,必須先找到該元素,所以要scan整個鏈表。
該元素可能重複,所以while 終止條件不能找到即停止,需要遍歷整個鏈表,遍歷整個鏈表爲 while 鏈表!=None
鏈表刪除元素:把 previous.next = current.next 即把當前current node刪除了
如果沒有previous怎麼辦(previous = None), 表示current就是head頭部,需要刪除頭部head節點,此時需要修改鏈表的head而不是previous.next
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
current = head
previous = None
found = False
while current != None:
if current.val == val:
if previous == None:
head = current.next
else:
previous.next = current.next
else:
previous = current
current = current.next
return head
3. Tips
上述解法超時。。。啊,氣死我了。
來看看咋解決:這裏的頭節點需要單獨判斷,如果需要刪除的是頭節點,需特殊處理,把鏈表的head(而不是previous node的next)指向下一個node。 如果這裏我們加一個無關緊要的假頭部dummy_head在head之前,使dummy.next = head, 那麼head就不需要特殊處理了。
同時往前存一個還有個好處,可以.next.next 推兩個,不需要創建previous保存前一個了,所以current 表示我們關注的上一個node, current.next纔是我們關注的node,current.next.next 是後一個值
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(-1)
dummy_head.next = head
current = dummy_head
while current.next != None:
if current.next.val == val:
current.next = current.next.next
else:
current = current.next
return dummy_head.next
理解鏈表這個數據結構,只需要head告訴鏈表的頭在哪就好了。 同樣 1 > 3 > 5 > 9 > 12
head指向1, return head 就是 13 5 9 12
head指向5, return head 就是 5 9 12