Remove element from linked list

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
class Solution {
public ListNode removeElements(ListNode head, int val) {

ListNode current = head;
ListNode prev = null;

while(current!=null){
if(current.val ==val){
if(prev!=null){
prev.next = current.next;
current.next = null;
current = prev.next;
}else{
head = head.next;
current = current.next;
}
}
else{
prev = current;
current = current.next;
}
}
return head;
}
}

Runtime: 1 ms, faster than 87.14% of Java online submissions for Remove Linked List Elements.

Memory Usage: 40.1 MB, less than 87.67% of Java online submissions for Remove Linked List Elements.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store