关于算法:算法-链表-虚拟头结点

起源:力扣(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;
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理