THINK FIRST·CODE LATER

← All labs

A singly linked list with index operations

Problem

Write SinglyList containing a generic class MyLinkedList<E>: a singly linked list with head, tail and size, and the methods

addFirst, addLast, add(index, e), get(index), set(index, e) (returns the old element), remove(index) (returns the removed element), indexOf, lastIndexOf, contains, size, toString.

An illegal index throws an IndexOutOfBoundsException with the message index 9, size 3.

main drives a list of strings with the commands add x, addFirst x, addAt i x, get i, set i x, remove i, indexOf x, lastIndexOf x, contains x, print, catching the exception. toString also shows the first and last elements, to verify head and tail. For the input

add b
add c
addFirst a
print
addAt 1 x
addAt 4 z
print
get 4
set 1 y
remove 0
remove 3
print
add b
indexOf b
lastIndexOf b
contains q
get 9

the program prints

3 element(s): [a, b, c] first a, last c
5 element(s): [a, x, b, c, z] first a, last z
get: z
set replaced x
removed a
removed z
3 element(s): [y, b, c] first y, last c
indexOf: 1
lastIndexOf: 3
contains: false
Refused: index 9, size 4
Final: [y, b, c, b] first y, last b

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-7-data-1.txt — first 14 lines of 17

add b
add c
addFirst a
print
addAt 1 x
addAt 4 z
print
get 4
set 1 y
remove 0
remove 3
print
add b
indexOf b
What your program must print for d10-7-data-1.txt
3 element(s): [a, b, c] first a, last c
5 element(s): [a, x, b, c, z] first a, last z
get: z
set replaced x
removed a
removed z
3 element(s): [y, b, c] first y, last c
indexOf: 1
lastIndexOf: 3
contains: false
Refused: index 9, size 4
Final: [y, b, c, b] first y, last b

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

Windows PowerShell does not understand <:

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