1. 程式人生 > >刪除鏈表中的元素 · Remove Linked List Elements

刪除鏈表中的元素 · Remove Linked List Elements

AR play 數據結構 integer opened public debug view 忘記

[抄題]:

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

[暴力解法]:

時間分析:

空間分析:

[思維問題]:

  1. 鏈表結構可能會改變,忘記用dummy node了,做鏈表題時提前牢記
  2. 兩個鏈表采用2個指針,一個鏈表用1個就夠了

[一句話思路]:

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  1. dummy初始化時,head = dummy是為了把head指針的指向從數字轉移到dummy,使其名正言順
  2. 理解dummy一直是空節點,最後返回的還是dummy.next

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

  1. 兩個鏈表采用2個指針,一個鏈表用1個就夠了

[復雜度]:Time complexity: O(n) Space complexity: O(1)

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

[關鍵模板化代碼]:

技術分享圖片
ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
    
        //remove
        while (head.next != null) {
            if (head.next.val == val) {
                head.next = head.next.next;
            }else {
                head = head.next;
            }
        }
        
        
return dummy.next;
dummy node

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

技術分享圖片
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: a ListNode
     * @param val: An integer
     * @return: a ListNode
     */
    public ListNode removeElements(ListNode head, int val) {
        //dummy
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
    
        //remove
        while (head.next != null) {
            if (head.next.val == val) {
                head.next = head.next.next;
            }else {
                head = head.next;
            }
        }
        
        return dummy.next;
    }
}
View Code

刪除鏈表中的元素 · Remove Linked List Elements