要求
Remove all elements from a linked list of integers that have value val
.
样例
Given 1->2->3->3->4->5->3
, val = 3, you should return the list as 1->2->4->5
代码
public class Solution {
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
ListNode current=head;
ListNode previous=head;
while(current != null)
{
if(current.val!=val)
{
previous=current;
current=current.next;
if(current==null)
break;
}else{
if(current==head)
{
head=head.next;
current=head;
}else{
previous.next=current.next;
current=current.next;
}
}
}
return head;
}
}