Anatomy
A linked list is a linear data structure that stores a collection of data elements dynamically.
A linked list consists of sequence of node. Each node contains two part:
- the value - whether it is an integer, string, or custom data type
- a reference (or pointer) to the next node in the sequence
A linked list contains a pointer to the first node called head
. It also contains a pointer to the last node called tail
.
This kind of linked list is called singly linked list.
public class LinkedList {
private Node head; // points to first node
private Node tail; // points to last node
private int length; // length of linked list (or number of nodes in list)
public LinkedList(int value) {
Node newNode = new Node(value);
head = newNode;
tail = newNode;
length = 1;
}
// getters and setters
static class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
}
}
}