203. 移除链表元素203. 移除链表元素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 输出:[]
class Solution {
public ListNode removeElements(ListNode head, int val) {
//虚拟头结点方式
//1.定义一个虚拟头结点
ListNode dummy = new ListNode(-1);
//2.虚拟头结点的下一个结点是head
dummy.next = head;
//3.定义一个遍历的结点
ListNode cur = dummy;
//4.遍历
while(cur.next != null){
//判断值是不是val
if(cur.next.val == val){
//进行删除
cur.next = cur.next.next;
}else{
//往下走
cur = cur.next;
}
}
//返回头结点
return dummy.next;
//非虚拟头结点方式
// //1.单独处理head的值时val的情况
// while(head != null && head.val == val){
// //移除head
// head = head.next;
// }
// if(head == null){
// return head;
// }
// 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;
}
}