力扣地址:https://leetcode.cn/problems/remove-linked-list-elements/
难度:☆☆
题目
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
Python代码
时间复杂度:O(n),其中 n 是链表的长度。
空间复杂度:O(1)。
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
# 方法:迭代
cur = dummy = ListNode(next = head) # 创建虚拟头节点
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next # 删除下一个节点
else:
cur = cur.next # 继续向后遍历链表
return dummy.next
Java代码
时间复杂度:O(n),其中 n 是链表的长度。
空间复杂度:O(1)。
class Solution {
public ListNode removeElements(ListNode head, int val) {
// 方法:迭代
ListNode dummy = new ListNode(0, 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;
}
}