LeetCode: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
输出:[]
通过虚拟头结点dummyHead
来删除指定节点,这样可以使得对所有的节点的处理都是用同样的方式
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode cur = dummyHead;
// 这里不需要再去判断 cur!= null 了,因为最开始时 cur = dummyHead 肯定是不为null的,如果进if则cur还是当前的cur 只是,cur.next变了;如果进else 也没关系 cur.next也不为空
// while(cur != null && cur.next != null){
while(cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummyHead.next;
}