In: Computer Science
Write a Java program that implements a queue in a hospital. I want your program to ask the user to enter the number of patients then enter the patient number starting from 110 till the end of the queue then print number of patients waiting in the queue.
Suppose you have a queue D containing the numbers (1,2,3,4,5,6,7,8), in this order. Suppose further that you have an initially empty Stack S. Give a code fragment that uses S, to store the elements in the order (8,7,6,5,4,3,2,1) in D.
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.Scanner;
public class HospitalQueue {
private Queue<Integer> patientQueue;
int numberOfPatients;
// Constructor to initialize values and create queue.
public HospitalQueue(int numberOfPatients){
this.numberOfPatients = numberOfPatients;
patientQueue = new LinkedList<>();
}
// Reverse queue using stack.
// Keep popping values from queue and adding to stack.
// Then keep popping values from stack and adding to queue to reverse the stack.
public void reverseQueue(Stack<Integer> s){
while(!patientQueue.isEmpty()){
int front = patientQueue.poll();
s.push(front);
}
while(!s.empty()){
int top = s.pop();
patientQueue.add(top);
}
}
public void add(int patientNumber){
patientQueue.add(patientNumber);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int numberOfPatients;
System.out.println("Enter number of patients");
numberOfPatients = sc.nextInt();
HospitalQueue hospital = new HospitalQueue(numberOfPatients);
// Entering patients till 110 to end of queue.
for(int count = 0; count < numberOfPatients; count++){
hospital.add(110 + count);
}
// Printing elements in queue before reversing-
System.out.println("Before reversing - ");
for(int patient : hospital.patientQueue){
System.out.printf("%d ", patient);
}
System.out.println("");
// We can use the reverseQueue function to reverse a queue using a stack.
Stack<Integer> s = new Stack<>();
hospital.reverseQueue(s);
// Printing elements in queue after reversing-
System.out.println("After reversing - ");
for(int patient : hospital.patientQueue){
System.out.printf("%d ", patient);
}
System.out.println("");
}
}
The output -
I have assumed somethings while implementing as you have not specified exactly how to implement. So if you want something done differently please comment and I shall change the code as required.
The code has been commented so you can understand the code better.
I would love to resolve any queries in the comments. Please consider dropping an upvote to help out a struggling college kid :)
Happy Coding !!