THINK FIRST·CODE LATER

← All labs

A stack on a resizing array

Problem

Write a class ResizingStack of ints on an array of initial capacity 2: push doubles the array when it is full; pop halves it when, after the pop, the stack is not empty and exactly one-quarter full. Count the elements copied by all resizes. pop and peek throw NoSuchElementException("stack is empty").

ResizingStackApp reads commands: push N pushes 1 … N, pop N pops N times and prints the last popped value, peek. After each command print the size and capacity, and at the end the number of operations and of copied elements.

For the input

push 5 peek pop 4 pop 1 pop 1

the program prints

push -> size 5, capacity 8
top: 5
peek -> size 5, capacity 8
last popped: 2
pop -> size 1, capacity 2
last popped: 1
pop -> size 0, capacity 2
error: stack is empty
pop -> size 0, capacity 2
Operations: 10, elements copied by resizing: 9

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-4-data-1.txt

push 5 peek pop 4 pop 1 pop 1
What your program must print for d10-4-data-1.txt
push -> size 5, capacity 8
top: 5
peek -> size 5, capacity 8
last popped: 2
pop -> size 1, capacity 2
last popped: 1
pop -> size 0, capacity 2
error: stack is empty
pop -> size 0, capacity 2
Operations: 10, elements copied by resizing: 9

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-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d10-4-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.