coolbud012

SortedLinkedList

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