Generate 100 random numbers and add them to a stack and a queue, after print out the content from both stack and queue, sort the data from both in ascending order, then print out again, after being sorted, and go through both the stack a queue and remove an element one at a time till empty then print out a message saying its empty. print out how much time it took to do this process, basically compare the stack and the queue. the stack should use an array with initial size of 50 and increase if need be. the queue should use a linkedlist.
stack should have: push, pop, front, peek, isEmpty
queue: enqueue, dequeue, front, peek, isEmpty
Write this code in Java
package com.test;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Stack;
public class DataUtility {
public static void main(String[] args) {
Random randNo = new Random();
Stack<Integer> stack = new
Stack<Integer>();
Queue<Integer> queue = new
LinkedList<>();
int radomCount=100;
for(int i=1;i<=radomCount;i++)
{
int
randInt1000=randNo.nextInt(1000);/// argument is range till the
number gets generate
stack.push(randInt1000);
queue.add(randInt1000);
}
System.out.println("Before sorting
stack and queue\n");
System.out.println("Element on
stack-->" + stack);
System.out.println("Element on
queue-->"+queue+"\n");
System.out.println("After Sorting
stack and queue\n");
sortStackElements(stack);// sorting
stack using recursion
queue=sortQueue(queue);
System.out.println("Element on
stack after sort-->" + stack);
System.out.println("Element on
queue after sort-->" + queue);
stack.clear();
queue.clear();
System.out.println("After Clearing
stack-->" +stack);
System.out.println("After Clearing
queue-->" +queue);
}
public static void
sortStackElements(Stack<Integer> stack) {
if (!stack.isEmpty()) {
int x =
stack.pop();
sortStackElements(stack);
insertElements(stack, x);
}
}
public static void
insertElements(Stack<Integer> stack, int element) {
if (stack.isEmpty() || element >
stack.peek()) {
stack.push(element);
return;
}
int tempInt = stack.pop();
insertElements(stack,
element);
stack.push(tempInt);
}
public static Queue sortQueue(Queue<Integer>
queue) {
PriorityQueue<Integer>
priQue=new PriorityQueue<>();
priQue.addAll(queue);
return priQue;
}
}
Get Answers For Free
Most questions answered within 1 hours.