Remove Linked List Elements
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
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode removeElements(ListNode head, int val) { 11 12 ListNode fakehead = new ListNode(-1); 13 fakehead.next = head; 14 ListNode n = fakehead; 15 16 if(head == null){ 17 return head; 18 } 19 while(n.next != null){ 20 if(n.next.val == val){ 21 n.next = n.next.next; 22 }else{ 23 n = n.next; 24 } 25 } 26 return fakehead.next; 27 } 28 }