Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to implement Singly LinkedList in Java ?.

Program to demonstrate implementation of Singly LinkedList in Java

public class ListNode {
 
  private int integerData;
  private ListNode nextNode;
 
  ListNode(int data)
  {
     this.integerData = data;
  }
 
  public int getIntegerData()
  {
     return integerData;
  }
 
  public void setIntegerData(int data)
  {
     this.integerData = data;
  }
 
  public ListNode getNextNode()
  {
     return nextNode;
  }
 
  public void setNextNode(ListNode next) 
  {
      this.nextNode = next;
  }
 
  public static int listLength(ListNode head)
  {
      int length = 0;
      ListNode currentNode = head;
  
      while(currentNode != null)
      {
 length++;
 currentNode = currentNode.getNextNode();
      }
  
      return length;
  }
 
  ListNode insert(ListNode head , ListNode nodeToInsert, int position)
  {
      if(head == null)
      {
   return nodeToInsert;
      }
  
      int size = listLength(head);
  
      if(position > size + 1 || position < 1)
      {
  System.out.println("Valid positions goes from 1 to "+ (size+1));
  return head;
      }
  
      if(position == 1)
      {
  nodeToInsert.setNextNode(head);
  head = nodeToInsert;
  return nodeToInsert;
      }
      else
      {
  ListNode previousNode = head;
  int count = 1;
  while (count < position - 1)
         {
      previousNode = previousNode.getNextNode();
      count++;
         }
   
  ListNode currentNode = previousNode.getNextNode();
  nodeToInsert.setNextNode(currentNode);
  previousNode.setNextNode(nodeToInsert);
      }
  
      return head;
    
   }
 
  ListNode delete( ListNode head , int position)
  {
     int size = listLength(head);
  
     if (position > size || position < 1)
     {
 System.out.println("Valid deletions position is from 1 to " + size);
 return head;
     }
  
     if(position == 1)
     {
 ListNode currentNode = head.getNextNode();
 head = null;
 return currentNode;
     }
     else
     {
 ListNode previousNode = head;
 int count = 1;
   
 while(count < position - 1)
 {
    previousNode = previousNode.getNextNode();
    count++;
 }
   
 ListNode currentNode = previousNode.getNextNode();
 previousNode.setNextNode(currentNode.getNextNode());
 currentNode.setNextNode(null);
     }
  
     return head;
  }

}


 
© 2021 Learn Java by Examples Template by Hubberspot