203.移除链表元素——学习笔记
题目:给你一个链表的头节点 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, 104] 内
- 1 <= Node.val <= 50
- 0 <= val <= 50
题目来源:力扣(LeetCode)链接
题解:
/**
* 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循环,找到第一个val不等于val的节点,并令其为head节点
while (head != null && head.val == val) {
head = head.next;
}
ListNode pre = head;//pre表示待删除节点的前一节点
while (pre != null) { //pre==null时表示到达链表的最后,循环停止
//这里的while循环是为了找到不等于val的节点
while (pre.next != null && pre.next.val == val) {
pre.next = pre.next.next;
}
//找到后pre后移,继续外层循环
pre = pre.next;
}
//返回头节点,如果头节点为空,那么返回的也为空
return head;
}
}

浙公网安备 33010602011771号