方案一:正常逻辑,不使用虚拟头节点或递归
/**
* 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) {
while(head != null && head.val==val){
ListNode delHead=head;
head=head.next;
delHead=null;
}
if(head == null)
return null;
ListNode prev=head;
while(prev.next!=null){
if(prev.next.val==val){
prev.next=prev.next.next;
}else{
prev=prev.next;
}
}
return head;
}
}
方案二:使用虚拟头节点
/**
* 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) {
//定义虚拟头节点
ListNode dummyHead=new ListNode(0);
dummyHead.next=head;
ListNode prev = dummyHead;
while(prev.next!=null){
if(prev.next.val==val){
prev.next=prev.next.next;
}else{
prev=prev.next;
}
}
return dummyHead.next;
}
}
方案三:递归
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return null;
ListNode res = removeElements(head.next,val);
if(head.val==val){
return res;
}else{
head.next=res;
return head;
}
}
}