Day41 移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
/**
* 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) {
// 处理头节点
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;
}
}
时间复杂度:O(n),其中 n 是链表的长度。每个节点最多被访问一次。
空间复杂度:O(1),仅使用了几个指针。