203. 移除链表元素

203. 移除链表元素
删除链表结点
方式1:直接在原链表删除
方式2:添加一个虚拟头结点,再删除

删除链表结点操作是通过前一个结点完成的,由于头结点没有前驱结点,所以头结点的删除需要单独的处理逻辑
通过添加一个虚拟头结点,链表中所有结点的删除操作相同
image

方式1

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // 单独处理头结点的删除
        while (head != null && head.val == val) {
            head = head.next;
        }
        // 删除其他结点
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return head;
    }
}
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // 单独处理头结点
        while (head != null && head.val == val) {
            head = head.next;
        }
        // 头结点已经为 null
        if (head == null) return head;
        // 处理其他结点
        ListNode prev = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.val == val) {
                prev.next = cur.next;
            } else {
                prev = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}

方式2

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // 设置一个虚拟的头结点
    ListNode dummy = new ListNode();
    dummy.next = head;

    ListNode cur = dummy;
    while (cur.next != null) {
        if (cur.next.val == val) {
            cur.next = cur.next.next;
        } else {
            cur = cur.next;        
        }
    }
    return dummy.next;
    }
}

递归

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // 假设 removeElements() 返回去除 val 元素的子链表
        // 在当前递归层接住后面删除 val 元素的子链表
        if (head == null) return null;
        head.next = removeElements(head.next, val);

        if (head.val == val) {
            return head.next;
        } 
        return head;
    }
}
posted @ 2025-10-17 12:13  Nickey103  阅读(3)  评论(0)    收藏  举报