【題目】
給定一個鏈表的頭節點head和一個整數num,請實現函數將值爲num的節點全部刪除。
【基本思路】
方法一。時間複雜度O(N),空間複雜度O(N)。
利用棧或者其他存儲結構。將不等於num的節點收集起來,收集完成後再重新連接即可。代碼實現如下:
#python3.5
def removeValue1(head, num):
if head == None:
return None
stack = []
while head != None:
if head.val != num:
stack.append(head)
head = head.next
while stack:
stack[-1].next = head
head = stack.pop()
return head
方法二。時間複雜度O(N),空間複雜度(1)。
首先從鏈表頭開始,找到第一個值不等於num的節點,作爲新的頭節點。之後繼續往後遍歷,將所有值爲num的節點刪除即可。代碼實現如下:
def removeValue2(head, num):
if head == None:
return head
while head != None and head.val == num:
head = head.next
pre = head
cur = head
while cur != None:
if cur.val == num:
pre.next = cur.next
else:
pre = cur
cur = cur.next