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.

Example:



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

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

Remove Linked List Elements Java Program


Approach:
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 = head.next;
        if(head == null) return null;
        
        ListNode curr = head;
        while(curr.next != null){
            if(curr.next.val == val){
                curr.next = curr.next.next;
            }else{
                curr = curr.next;
            }
        }
        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.

Comments

Popular Posts from this Blog

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Anti Diagonals - The Coding Shala

First Missing Positive Solution - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala