Build a singly linked list
28 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Tracking head, tail, and size gives O(1) front insertion, O(1) back insertion, and O(1) size checks.
Add first and add last with head and tail
A node is one element of a linked structure: it stores a value and references (links) to other nodes, such as next in a linked list.
addFirst inserts a node before head, and addLast appends a node after the last one. Storing both Node head and Node tail makes insertions at both ends O(1); with only Node head, addLast(int val) walks the whole list in O(n) time.
void addFirst(int val) { head = new Node(val, head); if (tail == null) tail = head; // list was empty: the new node is also the tail size++;}
void addLast(int val) { Node n = new Node(val, null); if (tail == null) { head = tail = n; } // empty list: one node is both head and tail else { tail.next = n; tail = n; } // link after the old tail, no walking: O(1) size++;}Whenever you change a list with head and tail, check the empty-list case (head == null). When a list has one node, head and tail must point to that same node.
addFirst(int val): Sethead = new Node(val, head);. Iftail == null, settail = head;. Incrementsize++.addLast(int val): CreateNode n = new Node(val, null);. Iftail == null, sethead = tail = n;, else settail.next = n; tail = n;. Incrementsize++.
if (tail == null) tail = head; in addFirst leaves tail as null and breaks the next addLast call.Traverse, print, and search
To traverse a list without losing the front, never move head itself. Start a local variable Node curr = head; and advance curr = curr.next until curr == null.
Example 1 · Searching a Linked List: indexOf, contains, and get
public class SearchLinkedListDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static int indexOf(Node head, int target) { int idx = 0; for (Node curr = head; curr != null; curr = curr.next) { if (curr.val == target) { return idx; } idx++; } return -1; }
public static boolean contains(Node head, int target) { return indexOf(head, target) != -1; }
public static void main(String[] args) { Node head = new Node(12, new Node(24, new Node(36, new Node(24, null)))); System.out.println("indexOf(24) = " + indexOf(head, 24)); System.out.println("indexOf(36) = " + indexOf(head, 36)); System.out.println("indexOf(99) = " + indexOf(head, 99)); System.out.println("contains(12) = " + contains(head, 12)); }}indexOf(24) = 1 indexOf(36) = 2 indexOf(99) = -1 contains(12) = true
What this code does
indexOfreturns on the first node withcurr.val == target(index 1for24).- When
headisnullortargetis absent, the loop ends and returns-1.
Example 2 · Why while (curr != null) vs while (curr.next != null) Matters
public class LoopConditionTrapDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
static int countBuggy(Node head) { if (head == null) return 0; int count = 0; Node curr = head; while (curr.next != null) { // Stops BEFORE counting the last node! count++; curr = curr.next; } return count; }
static int countCorrect(Node head) { int count = 0; for (Node curr = head; curr != null; curr = curr.next) { count++; } return count; }
public static void main(String[] args) { Node head = new Node(10, new Node(20, new Node(30, null))); System.out.println("countBuggy: " + countBuggy(head)); System.out.println("countCorrect: " + countCorrect(head)); }}countBuggy: 2 countCorrect: 3
What this code does
while (curr.next != null)stops as soon ascurrreaches the tail node (30), so it misses the last node.for (Node curr = head; curr != null; curr = curr.next)visits all 3 nodes and handleshead == nullcleanly.
What the loops do:
while (curr != null)visits all n nodes and ends withcurr == null.indexOf(target)returns the first matching 0-based index, or-1if missing.contains(target)returnsindexOf(target) != -1.
Choose the loop condition based on where curr should stop:
- Use
while (curr != null)to visit every node (printing, summing, counting, or searching). - Use
while (curr.next != null)(whencurr != null) to stop on the last node. To search fortarget, walkcurrfromheadwhile countingindexfrom0. Returnindexwhencurr.val == target, or-1whencurrreachesnull.
Find the bug
Find the bug in each method
Select the line that is wrong.
This should count every node of the list.
Round 1 of 3Tracking the size
Without a size field, finding the length walks all n nodes from head in O(n) time.
Keep a private int size field: add 1 on insert and subtract 1 on remove. Now size() and isEmpty() run in O(1) time.
Example 3 · Complete SinglyLinkedList Class with addFirst, addLast, size, and toString
public class SinglyLinkedListDemo { static class SinglyLinkedList { private static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
private Node head; private Node tail; private int size;
public void addFirst(int val) { head = new Node(val, head); if (tail == null) { tail = head; } size++; }
public void addLast(int val) { Node n = new Node(val, null); if (tail == null) { head = tail = n; } else { tail.next = n; tail = n; } size++; }
public int size() { return size; }
@Override public String toString() { StringBuilder sb = new StringBuilder("["); for (Node curr = head; curr != null; curr = curr.next) { sb.append(curr.val); if (curr.next != null) sb.append(" -> "); } return sb.append("]").toString(); } }
public static void main(String[] args) { SinglyLinkedList list = new SinglyLinkedList(); System.out.println("Empty: " + list + " (size=" + list.size() + ")"); list.addLast(20); list.addFirst(10); list.addLast(30); list.addFirst(5); System.out.println("After adds: " + list + " (size=" + list.size() + ")"); }}Empty: [] (size=0) After adds: [5 -> 10 -> 20 -> 30] (size=4)
What this code does
list.addLast(20)on an empty list sets bothheadandtailtoNode(20).- Every
addFirstandaddLastruns in O(1) time without walking the list.
Three states every list method must keep correct:
- Empty list rule:
size == 0,head == null, andtail == null. - One-node rule:
size == 1,head == tail, andhead.next == null. - Multi-node rule:
size >= 2,head != tail, andtail.next == null.
Next step
Check your understanding
10 quick questions