Skip to main content
← Advanced CS Study Guide

Code Scholars Tutoring · Advanced CS

3.1 Nodes and References

How it works

A linked list is nodes each holding a value and a reference onward. There is no index, so position k costs k steps to reach.

Walk from the head, counting steps, and keep a reference to the previous node when you may need to modify.

Common error

Assuming constant-time access. That is an array property and does not survive the switch.

Worked example

Java snippets run inside a main method. Add import java.util.*; when collection types are used.

Java

class Node {
    int value; Node next;
    Node(int value, Node next) { this.value = value; this.next = next; }
}
Node head = new Node(4, new Node(7, null));
Node alias = head;
alias.value = 9;
System.out.println(head.value + ":" + head.next.value);

Output

9:7

Each node stores a value and a reference to its successor. Assigning head to alias copies the reference, so both names initially identify the same mutable node.

The head and alias point to the node containing 9, which links to 7 and then null.
After the value update, both references observe the same first node.

Exercises

3.1.1 · Explain

After alias = head.next, does assigning alias = null remove the second node from the list?

Show solution

No. It only changes the local alias variable. The link stored in head.next still refers to that node.

3.1.2 · Explain

What condition ends a straightforward singly linked traversal?

Show solution

The current reference becomes null after the last node, assuming the list has no cycle. A cycle requires different termination logic.

Open Java compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic