THINK FIRST·CODE LATER

← All labs

Linked-list surgery: middle, duplicates, reverse

Problem

Write LinkedOps with your own singly linked list (a Node class with value and next, plus head and tail references — no java.util lists). Read integers until the end of input, appending each with addLast. Then:

  1. print the list (1 -> 1 -> 2);
  2. print the middle value with the slow/fast pointer technique (for an even length, the second of the two middle nodes);
  3. remove every node equal to its predecessor and print how many were removed;
  4. reverse the list in place in one pass and print it;
  5. append 0 (this checks that your tail is still correct) and print.

For the input

1 1 2 3 3 3 4

the program prints

List:     1 -> 1 -> 2 -> 3 -> 3 -> 3 -> 4
Middle:   3
Removed 3 adjacent duplicate(s): 1 -> 2 -> 3 -> 4
Reversed: 4 -> 3 -> 2 -> 1
Add 0:    4 -> 3 -> 2 -> 1 -> 0

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

1 1 2 3 3 3 4
What your program must print for d10-3-data-1.txt
List:     1 -> 1 -> 2 -> 3 -> 3 -> 3 -> 4
Middle:   3
Removed 3 adjacent duplicate(s): 1 -> 2 -> 3 -> 4
Reversed: 4 -> 3 -> 2 -> 1
Add 0:    4 -> 3 -> 2 -> 1 -> 0

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

Windows PowerShell does not understand <:

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