THINK FIRST·CODE LATER

← All labs

A doubly linked list driven by commands

Problem

Implement your own doubly linked list of int values (fields head, tail, size; nodes with prev and next) — do not use java.util collections — and drive it with commands read from standard input until the input ends. There is one command per line:

Command Effect Output
addFirst x / addLast x insert x at the front / back none
removeFirst / removeLast remove at the front / back the removed value, or empty
insert i x insert x so that it gets index i (0 ≤ i ≤ size) none, or invalid index
delete i remove the element at index i (0 ≤ i < size) the removed value, or invalid index
size size <n>
print the list from head to tail, e.g. [0, 1, 2]
reverse the list from tail to head following prev, e.g. [2, 1, 0]

reverse only prints; it does not change the list. It exposes any prev or tail reference you forgot to update. Example:

addLast 1
addLast 2
addFirst 0
print
reverse
insert 2 9
print
delete 1
print

prints

[0, 1, 2]
[2, 1, 0]
[0, 1, 9, 2]
1
[0, 9, 2]

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

addLast 1
addLast 2
addFirst 0
print
reverse
insert 2 9
print
delete 1
print
reverse
size
What your program must print for d10-1-data-1.txt
[0, 1, 2]
[2, 1, 0]
[0, 1, 9, 2]
1
[0, 9, 2]
[2, 9, 0]
size 3

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

Windows PowerShell does not understand <:

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