Program to input a linked list and output the sorted linked list

Posted On // Leave a Comment
import java.util.*;

class ll{
static class node{
int data;
node next;
}
public static node insert(node h,int x){
node current =new node();
node temp = new node();
temp.data=x;
if(h==null)
{
temp.next=null;
h=temp;
}
else {
current = h;
while(current.next!=null)
current = current.next;
temp.next=null;
current.next=temp;
}
return h;
}
public static void display(node h){
node current =new node();
current = h;
while (current!=null)
{
if(current.next!=null)
System.out.print(current.data + "->");
else
System.out.print(current.data);
current=current.next;
}
}
public static node sort(node h){
node current =new node();
node temp = new node();
node navigate = new node();
current=h;
if(h==null)
return null;
else
{
while (current!=null){
navigate=current.next;
while(navigate!=null){
if(navigate.data<current.data)
{
temp.data=current.data;
current.data=navigate.data;
navigate.data=temp.data;
}
navigate=navigate.next;
}
current=current.next;
}
}
return h;
}
public static void main(String args[])
{
int k=0;
System.out.println("Program to input a linked list and output the sorted linked list.Print the output at each step");
node h = new node();
h=null;
while(k==0){
System.out.println("Add an element:(Enter 1 to add an element or 0 to exit)");
Scanner in = new Scanner(System.in);
int u =in.nextInt();
if(u==1)
{
System.out.println("Enter the data to insert:");
int data = in.nextInt();
h = insert(h,data);
display(h);
h=sort(h);
System.out.println("\n");
display(h);
System.out.println("\n");
}
else
k=1;
}
}
}

0 comments :

Post a Comment