博客 / 詳情

返回

算法 - 鏈表 - 虛擬頭結點

來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/...

給你一個鏈表的頭節點 head 和一個整數 val ,請你刪除鏈表中所有滿足 Node.val == val 的節點,並返回 新的頭節點 。
 

示例 1:


輸入:head = [1,2,6,3,4,5,6], val = 6
輸出:[1,2,3,4,5]
示例 2:

輸入:head = [], val = 1
輸出:[]
示例 3:

輸入:head = [7,7,7,7], val = 7
輸出:[]

來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/remove-linked-list-elements
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

方式1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head== null){
            return head;
        }

        while(head != null && head.val == val){
            head = head.next;
        }

        ListNode cursor = head;
        while(cursor != null && cursor.next != null){
            if(cursor.next!= null && cursor.next.val == val){
                cursor.next = cursor.next.next;
            }else 
                cursor = cursor.next;
        }

        return head;
    }
}

方式2:虛擬頭節點

不用判斷head,把head和其他節點一樣處理,返回虛擬節點的下一個節點即是head。
比方式1 更簡化代碼和邏輯。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {

        ListNode dummyHead = new ListNode(0, head);
        
        ListNode cursor = dummyHead;
        while(cursor != null && cursor.next != null){
            if(cursor.next!= null && cursor.next.val == val){
                cursor.next = cursor.next.next;
            }else 
                cursor = cursor.next;
        }

        return dummyHead.next;
    }
}
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.