How to delete a Node from Linked List in java

 

In our earlier tutorials we have seen lot of Linked List related questions and programs. On similar stage another question is how to delete a Node from a Linked List. Same way lets create a Linked List and try to delete a node from it with simple Java code.

How to delete a Node from Linked List in java


class NODE {

 int data;
 NODE next = null;

 public NODE(int data) {
  this.data = data;
 }
}

public class DeleteLLNode {
 
 public static void main(String[] args) {

  int array[] = new int[] { 11, 12, 13, 14, 15, 16, 17, 18 };
  int deleteNode = 15;
  
  DeleteLLNode obj = new DeleteLLNode();

  // Create linkedlist based all array values
  NODE start = obj.createLinkedList(array);
  
  // Print all node values before delete
  obj.printLinkedList(start);
  
  start = obj.deleteNode(start, deleteNode);

  // Print all node values after delete
  obj.printLinkedList(start);
 }

 /*
  * Create LinkedList and return the start pointer/node
  */
 public NODE createLinkedList(int[] array) {

  NODE start = null;
  NODE tmp = null;

  for (int i : array) {

   tmp = new NODE(i);

   if (start == null) {
    start = tmp;
   } else {
    NODE mover = start;
    while (mover.next != null) {
     mover = mover.next;
    }
    mover.next = tmp;
   }
  }
  return start;
 }
 
 /*
  *  Print all linked list node values 
  */
 public void printLinkedList(NODE start) {
  System.out.print("Linked List: ");
  while(start != null) {
   System.out.print(start.data +", ");
   start = start.next;
  }
  System.out.println();
 }

 /*
  * Delete Linked List node 
  */
 public NODE deleteNode(NODE start, int val) {
  NODE tmp = start;
  
  // If its first node to delete
  if(tmp != null && tmp.data == val) {
   start = start.next;
   return start;
  }
  
  NODE previous = null;
  while(tmp != null) {
   if(tmp.data == val) {
    previous.next = tmp.next;
   }
   previous = tmp;
   tmp = tmp.next;
  }
  return start;
 }
}


OUTPUT:


Linked List: 11, 12, 13, 14, 15, 16, 17, 18, 
Linked List: 11, 12, 13, 14, 16, 17, 18, 


No comments:
Write comments