Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode VHead = new ListNode(-1);
VHead.next = head;
ListNode p = VHead;
ListNode q = head;
while(q!=null){
if(q.val==val){
p.next = p.next.next;
q = p.next;
}
else{
p = p.next;
q = q.next;
}
}
return VHead.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {1,2,6,6,3,4,5,6};
ListNode head = new ListNode(a[0]);
ListNode p = head;
for(int i = 1;i<a.length;i++){
ListNode q = new ListNode(a[i]);
p.next = q;
p = q;
}
head = new Solution().removeElements(head, 6);
p = head;
while(p!=null){
System.out.println(p.val);
p = p.next;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}