I'm working through Algorithms Fourth Edition (Sedgewick) and am confused by some of the linked-list exercises which seem to be asking to implement static methods for the non-static nodes. For example,
1.3.27 Write a method
max()
that takes a reference to the first node in a linked list as argument and returns the value of the maximum key in the list. Assume that all keys are positive integers, and return0
if the list is empty.
or
1.3.31 Implement a nested class DoubleNode for building doubly-linked lists, where each node contains a reference to the item preceding it and the item following it in the list (
null
if there is no such item). Then implement static methods for the following tasks: insert at the beginning, insert at the end, remove from the beginning, remove from the end, insert before a given node, insert after a given node, and remove a given node.
As I understand (and confirmed by SO answers here and here) this isn't possible. As expected, Eclipse gives errors if I try to write a static method in the superclass:
public class DoublyLinkedList<Item> {
public static void insertStart(DoubleNode first) {
// implementation
}
private class DoubleNode {
Item item;
DoubleNode next;
DoubleNode previous;
}
}
(gives the error Cannot make a static reference to the non-static type DoubleNode
); or in the inner class:
public class DoublyLinkedList<Item> {
private class DoubleNode {
Item item;
DoubleNode next;
DoubleNode previous;
public static void insertStart(DoubleNode first) {
// implementation
}
}
}
(gives the error The method insertStart cannot be declared static; static methods can only be declared in a static or top level type
).
I could write the required methods as instance methods for the DoublyLinkedList
class, and this would seem most natural to me.
However, I feel that I might be missing out on something important here. The author explicitly states that the methods should be static, and also suggests taking a reference to the first node as an argument (which would be unnecessary for an instance method as the class will have an instance variable for the first node). What am I missing?