Pin It

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;
  }

}


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot