难度简单1116收藏分享切换为英文接收动态反馈
给你一个链表的头节点 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 输出:[]
注意:链表和数组不同,链表是分布存储的,依靠节点相互连接
思路:这个题目比较简单,就是删除链表中的元素,主要要注意的就是是否是头节点 被删除,有两种方案。
方案一:单独把首节点拿出来分开看单独处理,其他节点就按规格来算
方案二:添加一个新的首节点,全部都按一个规格来算
方案一:
/**
* 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) {
if(head==null){
return head;
}
while(head!=null && head.val==val){
head=head.next;
}
ListNode cur=head;
while(cur!=null){
while(cur.next!=null && cur.next.val==val){
cur.next=cur.next.next;
}
cur=cur.next;
}
return head;
}
}
方案二:
/**
* 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) {
if(head==null){
return head;
}
ListNode des = new ListNode(-1,head);
ListNode pre = des;
ListNode cur = head;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
}else{
pre=cur;
}
cur=cur.next;
}
return des.next;
}
}