Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,166 questions

40,722 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
...