coolbud012

SortedLinkedList

Oct 23rd, 2015
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. package chapter_4_linked_list;
  2.  
  3. public class SortedLinkedList {
  4.     private Node head;
  5.    
  6.     public void insertInSortedList(int data) {
  7.        
  8.         Node newNode = new Node(data);
  9.        
  10.         if(this.head == null) {
  11.             this.head = newNode;
  12.         }
  13.        
  14.         Node current = this.head;
  15.         if(current.getNextNode() == null) {
  16.                 current.setNextNode(newNode);
  17.                 return;
  18.         }
  19.        
  20.         while(current != null) {
  21.             if(current.getData() < newNode.getData() && current.getNextNode().getData() > newNode.getData()) {
  22.                 newNode.setNextNode(current.getNextNode());
  23.                 current.setNextNode(newNode);
  24.                 current = current.getNextNode();
  25.             }
  26.         }
  27.     }
  28.    
  29.     @Override
  30.     public String toString() {
  31.         String list = "{ ";
  32.  
  33.         /**
  34.          * Create a new node which will be the current node set it as the head
  35.          * element as we have to start from the head element
  36.          */
  37.         Node currentNode = this.head;
  38.  
  39.         // to go through all the nodes till the current node points to null
  40.         while (currentNode != null) {
  41.  
  42.             // get the data of the current node from the toString of the Node
  43.             // class
  44.             list += currentNode.toString() + ", ";
  45.  
  46.             // then we set / increase the currentNode as the next node until it
  47.             // reaches null
  48.             currentNode = currentNode.getNextNode();
  49.         }
  50.  
  51.         list += " }";
  52.  
  53.         return list;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment