452.Remove Linked List Elements
1.Description(Naive)
Remove all elements from a linked list of integers that have valueval
.
Example
Given1->2->3->3->4->5->3
, val = 3, you should return the list as1->2->4->5
2.Code
public ListNode removeElements(ListNode head, int val) {
if(head==null){
return head;
}
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode prev=dummy;
ListNode current=head;
while(current!=null){
if(current.val==val){
prev.next=current.next;
//注意这个时候因为中间删了一个值,所以prev还是不变的,只变了current
current=current.next;
}
else{
prev=prev.next;
current=current.next;
}
}
return dummy.next;
}
Last updated
Was this helpful?