Linked lists force students to reason about references instead of indexes. The core skill is not memorizing node code; it is learning how arrows change without losing part of the list.
The basic node model
class Node
{
private int data;
private Node next;
public Node(int data, Node next)
{
this.data = data;
this.next = next;
}
public int getData() { return data; }
public Node getNext() { return next; }
public void setNext(Node next) { this.next = next; }
}
A list is a chain. If head points to 10, and that node points to 20, then the only way to reach 20 is through the first node's next reference. If you overwrite that reference carelessly, 20 and everything after it can become unreachable.
Worked example: insert after the first larger value
Suppose the list is sorted and we want to insert value so the order stays sorted.
public void insertSorted(int value)
{
Node newNode = new Node(value, null);
if (head == null || value <= head.getData())
{
newNode.setNext(head);
head = newNode;
return;
}
Node current = head;
while (current.getNext() != null
&& current.getNext().getData() < value)
{
current = current.getNext();
}
newNode.setNext(current.getNext());
current.setNext(newNode);
}
The order of the last two lines matters. First the new node points to the rest of the list. Then the previous node points to the new node. Reversing the order can cut off the original tail.
Worked example: remove consecutive duplicates
For a sorted list, duplicates are adjacent. That means we can remove duplicates with one traversal.
public void removeAdjacentDuplicates()
{
Node current = head;
while (current != null && current.getNext() != null)
{
if (current.getData() == current.getNext().getData())
{
current.setNext(current.getNext().getNext());
}
else
{
current = current.getNext();
}
}
}
Notice the else. When a duplicate is removed, current stays in place because the next node may also be a duplicate.
Common traps
- Using
current.getNext().getData()without checkingcurrent.getNext() != null. - Moving
currentafter a removal and skipping a duplicate. - Forgetting that inserting at the head changes the
headreference itself. - Thinking
current = current.getNext()changes the list. It only moves the temporary reference.
Practice prompt
Trace removeAdjacentDuplicates on 1 -> 1 -> 1 -> 3 -> 3 -> 4. After each loop iteration, write the list and the value of current.
