Remove Nodes from Linked List | Linked List Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a singly linked list and an integer value, remove all nodes from a given linked list, whose value is equal to a given integer value.

Example 

Linked List

Input :- head = [5, 4, 10, 15, 1] , node = 4
Output :- [5, 10, 15, 1]
Input :- head = [5, 4, 10, 15, 1, 5, 6] , node = 5
Output :- [4, 10, 15, 1, 6]

Solution

We will traverse the linked list by checking the value of each node. If the value of a node is equal to the given value then we will assign the next value of the current node to the next of previous node and moved to the next node, otherwise, we will move to the next node.

Program

public class Main {

	public static void main(String[] args) {
		
		ListNode head = null;
		
		ListNode node = new ListNode(5);
		head = node;		
		node.next = new ListNode(4);
		node = node.next;		
		node.next = new ListNode(10);
		node = node.next;		
		node.next = new ListNode(15);
		node = node.next;		
		node.next = new ListNode(1);
		node = node.next;
		node.next = new ListNode(5);
		node = node.next;
		node.next = new ListNode(6);
		
		Main main = new Main();
		head = main.removeElements(head, 5);
		
		ListNode listNode = head;
		while(listNode != null) {
			System.out.print(listNode.value + ", ");
			listNode = listNode.next;
		}
	}
	
	/* Solution */
	public ListNode removeElements(ListNode head, int value) {
        ListNode current = head;
        ListNode previous = null;
        ListNode newHead = head;
        while(current != null){            
            if(current.value == value){
                if(previous != null){
                    previous.next = current.next;
                    current = current.next;
                }else {       
                    current = current.next;
                    newHead = current;                    
                }                
            }else {
                previous = current;
                current = current.next;
            }           
        }
        return newHead;
    }
	
	/* Definition of Linked List Node */
	public static class ListNode {		
		int value;
		ListNode next;
		
		public ListNode(int value) {
			this.value = value;
		}		
	}
}

Result

4, 10, 15, 1, 6,

That’s all for Remove Nodes from a Linked List in Java, If you liked it, please share your thoughts in a comments section and share it with others too.