203. 移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
输入:head = [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() {}
* 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) {
while(head!=null && head.val==val)
{
head=head.next;
}
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;
}
}
节点定义一定要记住哈!不然白板写算法,怕你写不出
定义一个新的虚拟头结点来进行删除操作,这个就不需要考虑头结点了
代码如下:
/**
* 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) {
ListNode dummyHead=new ListNode(0);
dummyHead.next=head;
ListNode cur=dummyHead;
while(cur.next!=null)
{
if(cur.next.val==val)
{
cur.next=cur.next.next;
}else{
cur=cur.next;
}
}
head=dummyHead.next;
return head;
}
}
备注:java不用考虑内存回收,jvm会进行相应的垃圾回收哦!但是jvm一定要足够熟练才行。