I’m reading this book and there is this chapter on liked list and it starts with the implementation of a single linked list, it goes like this:
Creating a Linked List:
class Node {
Node next = null;
int data;
public Node(int d) {
data = d;
}
void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
}
My questions:
First: I can’t understand how this works. Is this really that complex to understad it or I’m missing something?
Second: Can this “Node” class be considered a linked list? I know it’s missing some functionality but is this a linked list on it’s own?
Third: I’ve googled LinkedList implementations in java and glanced at the original class in java api and it’s a totally different approach. To what approach should I stick?
The problem with this code is that the
Nodeclass is a node and a linked list at the same time, which is confusing. Other than that it should be pretty straightforward.The
nextholds the next node in a list. If it is the last node, it holdsnull. Thedatais a data associated with this node, which in this case is of typeint(BTW it should befinal).This is a simple
constructorwhich just copies the argument to its field. It represent the head of the list and a list itself.This is where find the meet. I’ve rearranged the code a bit to make it easier to understand. The
appendToTailmethod adds a node at the and of the list. In the code above it traverses the list (starting withthiswhich is a head of the list) to find the last node (the one withnextfield set tonull).Here a new node is created and added as the next node to the current last thus making it the last node of the list.