THINK FIRST·CODE LATER

← All labs

A queue made of two stacks

Problem

Write a generic class TwoStackQueue<T> with two stacks: enqueue pushes on the inbox; dequeue pops from the outbox, and only when the outbox is empty pours the whole inbox into it (count each element moved as a transfer). An empty queue throws NoSuchElementException.

TwoStackQueueApp simulates a service desk: in NAME joins the queue, out serves the next person (served Lina or nobody is waiting). At the end print how many are still waiting, the number of transfers, and whether each element was moved at most once.

For the input

in A in B in C out in D out out out out

the program prints

served A
served B
served C
served D
nobody is waiting
Still waiting: 0
Enqueued 4, transfers between stacks: 4
Each element is moved at most once: true

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d10-5-data-1.txt

in A in B in C out in D out out out out
What your program must print for d10-5-data-1.txt
served A
served B
served C
served D
nobody is waiting
Still waiting: 0
Enqueued 4, transfers between stacks: 4
Each element is moved at most once: true

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d10-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content d10-5-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.