1 移除链表元素
class Solution {
public ListNode removeElements(ListNode head, int target) {
//不知道为什么用虚拟头节点做不出来
while (head != null && head.val == target) {
head = head.next;
}
//这里跳出循环有两种可能:head == null; 或head.val != target
//1 1 1 1 1 2 3 1 3 4 1
// 2 1 null
ListNode cur = head;
//cur 有可能是null
while (cur != null) {
while (cur.next != null && cur.next.val == target) {
cur.next = cur.next.next;
}
cur = cur.next;
}
return head;
这里我遇到了一个问题:为什么循环不能这么写?
也就是这样
解答:因为这样的话,内层循环时,
如果指针已经把尾节点删了,此时cur.next ==null,
再进入内循环时,却又执行了cur.next.val