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

39次阅读

共计 1362 个字符,预计需要花费 4 分钟才能阅读完成。

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

正文完
 0