Using Collections, implement a data structure for storing numbers(int) in such a fashion that they can be accessed either in the order in which they were added or in their natural sorted order (ascending).
Hint: The nodes should have two references.
Implement three cases, where the 1st case [insert] is for adding numbers into the data structure, 2nd case [ascendingorder] is for displaying the elements of data structure in ascending order and the 3rd case [insertionorder] is for displaying the elements of data structure the order of their insertion.
Hint: The nodes should have two references.
Implement three cases, where the 1st case [insert] is for adding numbers into the data structure, 2nd case [ascendingorder] is for displaying the elements of data structure in ascending order and the 3rd case [insertionorder] is for displaying the elements of data structure the order of their insertion.
Solution:
import java.util.Collections;
import java.util.Scanner;
import java.util.ArrayList;
public class ArrayListExample{
public static void main(String [] args)
{
ArrayList< Integer > al=new ArrayList< Integer >();
ArrayList< Integer > al2=new ArrayList< Integer >();
String st;
int j=0;
int num=0;
Scanner input = new Scanner(System.in);
while(true){
st=input.next();
if(st.equals("insert"))
j=1;
else if(st.equals("ascendingorder"))
j=2;
else if(st.equals("insertionorder"))
j=3;
else
j=0;
switch(j){
case 1: //Insert
num=input.nextInt();
al.add(num);
al2.add(num);
break;
case 2: //ascendingorder
if(al.isEmpty()){
System.out.println("Empty");
break;
}
Collections.sort(al);
for(Integer i : al){
System.out.print(i+" ");
}
System.out.println();
break;
case 3: //insertionorder
if(al2.isEmpty()){
System.out.println("Empty");
break;
}
for(Integer i : al2){
System.out.print(i+" ");
}
System.out.println();
break;
default:
System.out.println("Invalid input!!");
break;
}
}
}
}

No comments:
Post a Comment