Linked Lists with Nodes |
Linked list is composed of series of nodes, each of which has a reference to the next.
Must provide SinglyLinkedListElement class representing the nodes, and then construct LinkedList class using those nodes. Notice that SinglyLinkedListElement is a recursive structure as it contains an element also of type SinglyLinkedListElement. Unlike previous examples, we do not bother to introduce an interface and base and recursive classes. We do this to better match traditional approaches to linked lists, though we could have taken an approach more similar to those we saw earlier in the text.
See LinkedList example.
In the LinkedList class notice all of the effort that went on in the methods to take care of boundary cases, e.g., adding or removing the first or last element in list.
Most common errors in working with linked structures are ignoring these cases.
Notice also that we implemented the get() method, but did not implement getFirst or getLast. That is because we inherited those methods from the AbstractList class.
Linked Lists with Nodes |