coolbud012

SortedLinkedList

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