LC-203

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

示例 1:

输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

迭代

    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }

虚拟头节点
没有虚拟 需要判断头节点的值是否为 val,并且处理头节点的代码逻辑与处理其它节点(非头节点)的代码逻辑特别相似,有没有方法使得代码更优美并且能避免对头节点的判断呢?

答案是有的。可以通过在头节点的前面增加虚拟头节点,这样头节点就跟其它节点一样了,不需要单独拎出来考虑,但是需要注意的是返回的时候,需要返回虚拟头节点的下一节点而不是虚拟头节点。

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummyHead = new ListNode(0);  
        dummyHead.next = head;
        
        ListNode cur = dummyHead;  
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return dummyHead.next;
    }
}
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        dummyHead = ListNode(-1) 
        dummyHead.next = head 
        cur = dummyHead 
        while cur.next: 
            if cur.next.val == val: 
                cur.next = cur.next.next 
            else: 
                cur = cur.next 
        return dummyHead.next
posted @ 2022-03-11 19:13  Ricardo_ML  阅读(41)  评论(1编辑  收藏  举报