在單鏈表中刪除指定值的節點
給定一個鏈表的頭節點head和一個整數num,實現一個函數刪除鏈表中值為num的所有節點。例如,鏈表為 1->2->3->4->null ,num 為3,刪除后,鏈表變為 1->2->4->null。
【解析】
方法一:使用棧或者其他容器收集節點的方法,其時間復雜度是 O(N),空間復雜度是O(N)將值不等於num的節點用棧收集起來,收集完成后重新連接即可。最后將棧底的節點作為新的頭節點返回。
方法二:不使用任何容器,直接調整的方法,其時間復雜度是 O(N),空間復雜度是O(1)
首先必須確保頭節點的值不為null,確保頭節點的值后,然后遍歷后面的
如果后面的值為num,則pre.next = cur.next
如果后面的值不為num,則 pre = cur
package com.test; import com.test.ListNode; import java.util.Stack; /** * Created by Demrystv. */ public class RemoveListNodeOfValue { /** * 方法一,使用棧或者其他容器收集節點的方法,其時間復雜度是 O(N),空間復雜度是O(N) */ public ListNode removeValue1(ListNode head, int num) { Stack<ListNode> stack = new Stack<ListNode>(); while (head != null) { if (head.val != num) { stack.push(head); } head = head.next; } while (!stack.isEmpty()) { stack.peek().next = head; head = stack.pop(); } return head; } /** *方法二,不使用任何容器,直接調整的方法,其時間復雜度是 O(N),空間復雜度是O(1) */ public ListNode removeValue2(ListNode head, int num){ while (head != null){ if (head.val != num){ break; } head = head.next; } ListNode pre = head; ListNode cur = head; while (cur != null){ if (cur.val == num){ pre.next = cur.next; }else { pre = cur; } cur = cur.next; } return head; } }