Find the Middle Node
mediumQuestion 452You 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, so print one after the last line.
Hints4 available
Sign in to use hintsTopics
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.