Remove Linked List Elements Java Program - The Coding Shala

Home >> Interview Questions >> Remove Linked list elements

Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.


Input:  1->2->6->3->4->5->6, val = 6

Output: 1->2->3->4->5

Remove Linked List Elements Java Program

Remove head if match and iterate through the linked list if match skips that node.

Java Code 

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while(head != null && head.val == val) head =;
        if(head == null) return null;
        ListNode curr = head;
        while( != null){
            if( == val){
                curr =;
        return head;

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala