【陪伴式刷题】Day 3|链表|203. 移除链表元素(Remove Linked List Elements)

73 阅读1分钟

刷题顺序按照代码随想录建议

题目描述

英文版描述

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1Output: []

Example 3:

Input: head = [7,7,7,7], val = 7Output: []

Constraints:

  • The number of nodes in the list is in the range [0, 10(4)].
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

英文版地址

leetcode.com/problems/re…

中文版描述

给你一个链表的头节点 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输出: []

提示:

  • 列表中的节点数目在范围 [0, 10(4)]
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

中文版地址

leetcode.cn/problems/re…

解题方法

俺这版

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode pre = new ListNode();
        pre.next = head;
        ListNode cur = pre;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }

        }
        return pre.next;
    }
}

复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(1)

官方版

递归

class Solution {
    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;
    }
}
复杂度分析
  • 时间复杂度:O(n),其中 n 是链表的长度。递归过程中需要遍历链表一次。
  • 空间复杂度:O(n),其中 n 是链表的长度。空间复杂度主要取决于递归调用栈,最多不会超过 nnn 层。