Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode RemoveElements(ListNode head, int val) {
ListNode temp = head;
if(head == null){
return head;
}
if(head.next == null){
if(head.val==val){
return null;
}
return head;
}
while(temp.next!=null){
if(temp.next.val==val){
temp.next = temp.next.next;
}
else{
temp = temp.next;
}
}
//check if first node is having given value
if(head.val==val){
head = head.next;
}
return head;
}
}
Time Complexity: O(n)
Space Complexity: O(1)


