Delete a Node in Linked List | Linked List Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a node of the singly linked list, write a program to delete the given node.

Note :- Given node will not be a tail of singly linked list.

Example 

Linked List

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

Solution

Since only the node to be deleted is given as input, we can not delete this node as we do not have access to its previous node. So only option is to delete the value of given node, for this we will recursively copy the value to next node to current node and in the end, delete the last node of linked list.

Program

public class Main {

	public static void main(String[] args) {
		
		ListNode head = null;
		
		ListNode node = new ListNode(5);
		head = node;		
		ListNode node4 = new ListNode(4);
		node.next = node4;
		node = node.next;		
		ListNode node10 = new ListNode(10);
		node.next = node10;
		node = node.next;		
		ListNode node15 = new ListNode(15);
		node.next = node15;
		node = node.next;		
		ListNode node1 = new ListNode(1);
		node.next = node1;
		
		Main main = new Main();
		main.deleteNode(node4);
		
		ListNode listNode = head;
		while(listNode != null) {
			System.out.print(listNode.value + ", ");
			listNode = listNode.next;
		}
	}

	/* Solution */
	public void deleteNode(ListNode node) {
        ListNode previous = null;
        while(node.next != null){            
            node.value = node.next.value;
            previous = node;
            node = node.next;            
        }
        previous.next = null;
    }
	
	/* Definition of Linked List Node */
	public static class ListNode {		
		int value;
		ListNode next;
		
		public ListNode(int value) {
			this.value = value;
		}		
	}
}

Result

5, 10, 15, 1,

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