← Back to Data Structures & Algorithms
Question 448
Remove the Last Node
Remove the Last Node
The tail pointer hands you the last node instantly, but it does not save you here: to unlink it you need the node BEFORE it, and a singly linked node cannot look back. So this stays an O(n) walk.
Requirements:
1. removeLast() unlinks the last node and returns its value.
2. On an empty list it returns -1.
3. When only one node remains, head and tail both become null.
4. Otherwise walk to the node whose next is tail, cut its link, and move tail onto it. Keep size correct.
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:
30 10 -> 20 -> null 2 20
= newline. The output ends with a newline — 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.