删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode temp = head;
//判断第一个节点
while (temp.val == val) {
if (head.next == null) return null;
head = head.next;
temp = head;
}
//之后的节点
while (temp.next != null) {
if (temp.next.val == val) {
//跳过符合条件的节点
temp.next = temp.next.next;
//如果到最后节点了就跳出循环
if (temp.next == null) break;
//如果交换了,直接进入下次循环,复制交换的也是符合条件的
continue;
}
temp = temp.next;
}
return head;
}
}
在while外定义一个链表变量temp2,然后把while里的temp.next替换成temp2就变成双指针了,思路一样。