Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Liquid Web Managed Dedicated Server: RAID 1 SSD with 16GB of RAM minimum! 24/7 On-Site Heroic Support! Industry-Leading SLA!

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Liquid Web Cloud VPS Hosting

8,512 questions

11,796 answers

573 users

How to build sorted linear (singly) linked list and insert new items in sorted order with Java

1 Answer

0 votes
package javaapplication1;

public class JavaApplication1 {
  
    Node head;  
 
    class Node
    {
        int n;
        Node next;
        Node(int number) {n = number; next = null; }
    }
 
    void insertSorted(Node new_node)
    {
        Node current;
 
        if (head == null || head.n >= new_node.n)
        {
            new_node.next = head;
            head = new_node;
        }
        else 
        {
            current = head;
            while (current.next != null &&current.next.n < new_node.n)
                  current = current.next;
 
            new_node.next = current.next;
            current.next = new_node;
         }
    }
 
    Node createNode(int n)
    {
       Node N = new Node(n);
       return N;
    }
 
    void printLinkedList()
    {
        Node tmp = head;
        while (tmp != null)
        {
           System.out.print(tmp.n + " ");
           tmp = tmp.next;
        }
    }
    
    public static void main(String[] args) {
         
        JavaApplication1 linkedlist = new JavaApplication1();
        Node new_node;
        
        new_node = linkedlist.createNode(13);
        linkedlist.insertSorted(new_node);
        
        new_node = linkedlist.createNode(9);
        linkedlist.insertSorted(new_node);
        
        new_node = linkedlist.createNode(2);
        linkedlist.insertSorted(new_node);
        
        new_node = linkedlist.createNode(3);
        linkedlist.insertSorted(new_node);
        
        new_node = linkedlist.createNode(6);
        linkedlist.insertSorted(new_node);
        
        new_node = linkedlist.createNode(10);
        linkedlist.insertSorted(new_node);
        
        new_node = linkedlist.createNode(5);
        linkedlist.insertSorted(new_node);
        
        linkedlist.printLinkedList();
    }
}
    
/*
run:
   
2 3 5 6 9 10 13
    
*/

 




answered Jun 25, 2017 by avibootz
...