package LinedList;
public class RemoveLinkedListElements {
//解法一:循环
public ListNode removeElements(ListNode head, int val) {
while (head!=null&&head.val==val){
ListNode temp=head;
head=temp.next;
temp.next=null;
}
if (head==null)
return null;
ListNode previous=head;
while (previous.next!=null){
if (previous.next.val==val){
ListNode temp=previous.next;
previous.next=temp.next;
temp.next=null;
}
else{
previous=previous.next;
}
}
return head;
}
//解法二,使用虚拟头节点的循环。
public ListNode removeElements2(ListNode head, int val) {
ListNode dummyHead=new ListNode(-1);
dummyHead.next=head;
ListNode previous=dummyHead;
while (previous.next!=null){
if (previous.next.val==val){
ListNode temp=previous.next;
previous.next=temp.next;
temp.next=null;
} else {
previous=previous.next;
}
}
return dummyHead.next;
}
//解法三:使用递归。
public ListNode removeElements3(ListNode head, int val) {
if(head==null)
return null;
head.next=removeElements(head.next,val);
return head.val==val?head.next:head;
}
}