CJCoding With Joseph
15free / daySign inCreate account

Find the Middle Node

You could call size() and walk half of it, but one pass is enough: move slow one node at a time and fast two, and when fast runs off the end slow is standing on the middle. The cursors are already declared.

Requirements:
1. middle() returns the value of the middle node, or -1 on an empty list.
2. Advance fast two nodes for every one that slow advances, and stop when fast or fast.next is null.
3. On an even-length list this lands on the SECOND of the two middle nodes.

The Node class is provided - do not rename it and do not add public to it, because a Java source file may contain only one public class.

Do NOT write a main method.

Expected Output:

-1
30
5
10 -> 20 -> 30 -> 40 -> 50 -> null

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsLinked Lists
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.