Skip to main content

Java Collections

LinkedList

Complete lesson for LinkedList using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — LinkedList

Section: Java Collections. LinkedList — a doubly linked list that works as a List, Queue, Stack, and Deque: nodes, methods, iteration, internals, complexity, and a full ArrayList vs LinkedList comparison with real-life examples.

What is LinkedList?

  • LinkedList in java.util stores elements in separate nodes. Each node knows its previous and next node, forming a doubly linked list.
  • It implements both List (index-based list) and Deque (double-ended queue), so it can act as a list, a queue, a stack, or a deque.
  • Adding or removing at the front or back is O(1). Reaching the element at index i needs walking node by node, which is O(n).
  • Real life: a train. Coaches are linked by couplings. Attaching or detaching a coach at either end is quick, but to reach coach 7 you must walk through coaches 1 to 6.
import java.util.LinkedList;

public class TrainLinkedList {
    public static void main(String[] args) {
        LinkedList<String> train = new LinkedList<>();
        train.add("S1");
        train.add("S2");
        train.addFirst("Engine");          // attach at the front: O(1)
        train.addLast("Guard");            // attach at the back: O(1)
        train.add(2, "Pantry");            // walk to position 2, then link: O(n)
        System.out.println(train);         // [Engine, S1, Pantry, S2, Guard]

        train.removeFirst();               // detach the engine for maintenance
        train.removeLast();                // detach the guard van
        System.out.println(train);         // [S1, Pantry, S2]
        System.out.println("First: " + train.getFirst() + ", last: " + train.getLast());
    }
}

How a doubly linked list looks

  • Each node holds three things: a reference to the previous node, the element (item), and a reference to the next node.
  • The list keeps references to the first and last nodes and a size counter, so getFirst(), getLast(), and size() are O(1).
  • Nodes can live anywhere in memory; only the links connect them. There is no shifting when you add or remove, only re-linking.
  • Real life: a human chain where each person holds the hands of the person in front and behind. To add someone, only two neighbours change their grip.
   first                                              last
     |                                                  |
     v                                                  v
 +------------------+   +------------------+   +------------------+
 | prev: null       |<--| prev             |<--| prev             |
 | item: "Engine"   |   | item: "S1"       |   | item: "Guard"    |
 | next ------------|-->| next ------------|-->| next: null       |
 +------------------+   +------------------+   +------------------+

 // Inside java.util.LinkedList (simplified):
 private static class Node<E> {
     E item;
     Node<E> next;
     Node<E> prev;
 }

Features of LinkedList

FeatureMeaning
StructureDoubly linked list of nodes
InterfacesList, Deque (and so Queue), Cloneable, Serializable
OrderKeeps insertion order
DuplicatesAllowed
nullAllowed (unlike ArrayDeque)
Index accessSupported but O(n): walks from the nearer end
EndsO(1) add, remove, and peek at both ends
CapacityNo capacity and no resizing; one node per element
Thread-safeNo
IteratorsFail-fast; also descendingIterator() and two-way ListIterator

Creating a LinkedList

  • There are only two constructors: an empty list, or a copy of another collection. There is no capacity constructor because nothing needs to be pre-allocated.
  • Declare the variable by the role you need: List for list operations, Queue for FIFO, Deque for stack or double-ended use, or LinkedList for everything.
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class CreateLinkedList {
    public static void main(String[] args) {
        LinkedList<String> all = new LinkedList<>();                 // full API: List + Deque
        List<String> asList = new LinkedList<>(List.of("A", "B"));   // copy constructor, used as a List
        Queue<String> asQueue = new LinkedList<>();                  // used as a FIFO queue
        Deque<String> asDeque = new LinkedList<>();                  // used as a stack or deque

        all.addFirst("x");
        asList.add(1, "mid");
        asQueue.offer("token-1");
        asDeque.push("page-1");
        System.out.println(all + " " + asList + " " + asQueue + " " + asDeque);
        // [x] [A, mid, B] [token-1] [page-1]
    }
}

LinkedList methods

MethodWhat it doesTime
add(e) / addLast(e) / offer(e)Adds at the endO(1)
addFirst(e) / offerFirst(e) / push(e)Adds at the frontO(1)
add(i, e)Inserts at index iO(n)
get(i) / set(i, e)Reads or replaces at index iO(n)
getFirst() / getLast()First or last element (throws if empty)O(1)
peekFirst() / peekLast() / peek()First or last element (null if empty)O(1)
removeFirst() / pop() / remove()Removes the first element (throws if empty)O(1)
pollFirst() / poll()Removes the first element (null if empty)O(1)
removeLast() / pollLast()Removes the last elementO(1)
remove(i) / remove(o)Removes by index or first matching valueO(n)
removeFirstOccurrence(o) / removeLastOccurrence(o)Removes the first or last matchO(n)
contains(o) / indexOf(o) / lastIndexOf(o)Searches by equalsO(n)
size() / isEmpty() / clear()Count, empty check, remove allO(1) / O(1) / O(n)
descendingIterator()Iterates from last to firstO(1) to create
listIterator()Two-way cursor with add, set, removeO(1) per step
reversed() (Java 21)Reverse-ordered viewO(1) to create

Differences between throwing and null-returning Deque methods

  • Deque methods come in pairs. One throws NoSuchElementException when the list is empty; the other returns null (or false) so you can check safely.
OperationThrows exception when emptyReturns special value
Insert at frontaddFirst(e)offerFirst(e) returns true or false
Insert at endaddLast(e)offerLast(e) / offer(e)
Remove from frontremoveFirst() / remove() / pop()pollFirst() / poll() returns null
Remove from endremoveLast()pollLast() returns null
Look at frontgetFirst() / element()peekFirst() / peek() returns null
Look at endgetLast()peekLast() returns null

Adding, accessing, and removing elements

  • Use addFirst and addLast for the ends, add(i, e) for a position, and get, getFirst, peekLast to read.
  • Remove with removeFirst, pollLast, remove(index), or remove(value).
  • Real life: a party playlist where you push a song to the top, add one at the end, and skip finished songs from the front.
import java.util.LinkedList;

public class PlaylistOps {
    public static void main(String[] args) {
        LinkedList<String> playlist = new LinkedList<>();
        playlist.add("Kesariya");
        playlist.add("Jai Ho");
        playlist.addFirst("Vande Mataram");          // play this first
        playlist.addLast("Naatu Naatu");
        playlist.add(2, "Chaiyya Chaiyya");          // insert at position 2
        System.out.println(playlist);
        // [Vande Mataram, Kesariya, Chaiyya Chaiyya, Jai Ho, Naatu Naatu]

        System.out.println(playlist.getFirst());     // Vande Mataram
        System.out.println(playlist.get(3));         // Jai Ho (walks node by node)
        System.out.println(playlist.peekLast());     // Naatu Naatu
        playlist.set(1, "Kesariya (Acoustic)");

        playlist.remove("Jai Ho");                   // by value
        playlist.removeFirst();                      // song finished
        String last = playlist.pollLast();           // remove from the end
        System.out.println(last + " removed; now " + playlist);
        // Naatu Naatu removed; now [Kesariya (Acoustic), Chaiyya Chaiyya]
    }
}

LinkedList as a Queue (FIFO)

  • A queue serves elements in the order they arrive: first in, first out. Use offer to join the line, poll to serve, and peek to see who is next.
  • Real life: a bank token line. Token 1 is served first; new customers join at the back.
import java.util.LinkedList;
import java.util.Queue;

public class BankQueue {
    public static void main(String[] args) {
        Queue<String> line = new LinkedList<>();
        line.offer("Token 1 - Asha");
        line.offer("Token 2 - Ravi");
        line.offer("Token 3 - Kiran");
        System.out.println("Next: " + line.peek());          // Token 1 - Asha (not removed)

        while (!line.isEmpty()) {
            System.out.println("Serving " + line.poll());    // first come, first served
        }
        System.out.println(line.poll());                     // null: empty queue, no exception
    }
}

LinkedList as a Stack (LIFO)

  • A stack serves the most recent element first: last in, first out. Use push, pop, and peek (all work on the front of the list).
  • Real life: the undo button. The last action you did is the first one undone.
import java.util.Deque;
import java.util.LinkedList;

public class UndoStack {
    public static void main(String[] args) {
        Deque<String> undo = new LinkedList<>();
        undo.push("typed Hello");
        undo.push("made it bold");
        undo.push("changed colour");
        System.out.println("Last action: " + undo.peek());   // changed colour
        System.out.println("Undo: " + undo.pop());           // changed colour
        System.out.println("Undo: " + undo.pop());           // made it bold
        System.out.println("Remaining: " + undo);            // [typed Hello]
    }
}

LinkedList as a Deque (both ends)

  • A deque lets you add and remove at both ends. That makes problems like palindrome checking natural: compare the front and back, then move inward.
  • Real life: a metro coach with doors at both ends; people can enter or leave from either side.
import java.util.Deque;
import java.util.LinkedList;

public class PalindromeCheck {
    static boolean isPalindrome(String text) {
        Deque<Character> dq = new LinkedList<>();
        for (char c : text.toLowerCase().toCharArray()) {
            if (Character.isLetterOrDigit(c)) dq.addLast(c);
        }
        while (dq.size() > 1) {
            if (!dq.pollFirst().equals(dq.pollLast())) return false;   // compare both ends
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Malayalam"));                   // true
        System.out.println(isPalindrome("Was it a car or a cat I saw"));  // true
        System.out.println(isPalindrome("LearnCodeGuru"));                // false
    }
}

Iterating a LinkedList

  • Use for-each or an Iterator to go forward, descendingIterator() to go backward, and ListIterator to insert, replace, or remove at the cursor in O(1).
  • Never loop with get(i) on a LinkedList: each get walks from an end, so the loop becomes O(n²).
  • Real life: metro stops. You travel forward, return in reverse, and a new stop can be inserted between two existing ones.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class MetroStops {
    public static void main(String[] args) {
        LinkedList<String> stops = new LinkedList<>(List.of("Ameerpet", "Begumpet", "Paradise", "Secunderabad"));

        for (String s : stops) System.out.print(s + " -> ");            // forward journey
        System.out.println("END");

        Iterator<String> back = stops.descendingIterator();             // return journey
        while (back.hasNext()) System.out.print(back.next() + " -> ");
        System.out.println("END");

        ListIterator<String> it = stops.listIterator();
        while (it.hasNext()) {
            if (it.next().equals("Begumpet")) {
                it.add("Rasoolpura");                                    // inserted at the cursor in O(1)
            }
        }
        System.out.println(stops);   // [Ameerpet, Begumpet, Rasoolpura, Paradise, Secunderabad]

        // Avoid: for (int i = 0; i < stops.size(); i++) stops.get(i);   // O(n^2)
    }
}

Differences between ArrayList and LinkedList

  • Real life: an ArrayList is like numbered theatre seats — you can walk straight to seat 25, but adding a seat in the middle means everyone shifts. A LinkedList is like train coaches — attaching or detaching at the ends is easy, but finding coach 25 means walking through the train.
PointArrayListLinkedList
Internal structureDynamic (resizable) arrayDoubly linked list of nodes
InterfacesList, RandomAccessList, Deque (so also Queue)
get(i) / set(i, e)O(1) — direct indexO(n) — walks from the nearer end
Add at endAmortized O(1) (occasional resize and copy)O(1)
Add / remove at beginningO(n) — shifts every elementO(1)
Add / remove in the middle by indexO(n) — shiftingO(n) to walk there, then O(1) to relink
Add / remove at an iterator positionO(n) — shiftingO(1)
Remove last elementO(1)O(1)
contains / indexOfO(n)O(n)
Memory per elementOne reference in an array (plus some spare capacity)A node object with item, prev, and next (about 24 extra bytes)
ResizingCopies to a 1.5 times bigger array when fullNever resizes; allocates one node per element
Capacity constructorYes: new ArrayList<>(1000)No
CPU cache friendlinessExcellent — elements are side by sidePoor — nodes are scattered in memory
Use as queue or stackNot directlyYes: offer, poll, push, pop
Reverse iterationlistIterator(size())descendingIterator()
null elementsAllowedAllowed
Thread-safeNoNo
IteratorFail-fastFail-fast
Best forReading by index, looping, adding at the end (most programs)Frequent add or remove at both ends or at a cursor
Real lifeNumbered theatre seatsTrain coaches linked together
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListRace {
    static long time(Runnable task) {
        long start = System.nanoTime();
        task.run();
        return (System.nanoTime() - start) / 1_000_000;
    }

    public static void main(String[] args) {
        int n = 50_000;
        List<Integer> arrayList = new ArrayList<>();
        LinkedList<Integer> linkedList = new LinkedList<>();

        System.out.println("Add at front - ArrayList:  "
            + time(() -> { for (int i = 0; i < n; i++) arrayList.add(0, i); }) + " ms");
        System.out.println("Add at front - LinkedList: "
            + time(() -> { for (int i = 0; i < n; i++) linkedList.addFirst(i); }) + " ms");

        System.out.println("Get by index - ArrayList:  "
            + time(() -> { long s = 0; for (int i = 0; i < n; i++) s += arrayList.get(i); }) + " ms");
        System.out.println("Get by index - LinkedList: "
            + time(() -> { long s = 0; for (int i = 0; i < n; i++) s += linkedList.get(i); }) + " ms");
        // Typical result: LinkedList wins add-at-front; ArrayList wins get-by-index by a huge margin
    }
}

When to use ArrayList vs LinkedList

SituationChooseWhy
Read elements by index oftenArrayListO(1) access instead of O(n)
Mostly add at the end and loopArrayListCompact and cache friendly
Large lists with tight memoryArrayListNo per-node overhead
Queue or stack only (ends)ArrayDeque (or LinkedList)ArrayDeque is usually faster; LinkedList also works
Need a queue that allows nullLinkedListArrayDeque rejects null
Many inserts or removes while walking with an iteratorLinkedListO(1) changes at the cursor
Need both List and Deque behaviour on one objectLinkedListOnly class that is both
Not sureArrayListBest default in real programs; measure before switching
L2

Advanced — LinkedList

How LinkedList works internally

  • Fields: Node<E> first, Node<E> last, and int size. Each Node has item, prev, and next.
  • addLast creates a node whose prev is the old last node, then links the old last node forward to it. addFirst does the mirror image.
  • get(i) calls an internal node(index) method: if the index is in the first half it walks forward from first, otherwise backward from last. At most n/2 steps, still O(n).
  • Removing a node just reconnects its neighbours and clears its links so the garbage collector can free it.
import java.util.NoSuchElementException;

public class MiniLinkedList<E> {
    private static class Node<E> {
        E item;
        Node<E> prev;
        Node<E> next;

        Node(Node<E> prev, E item, Node<E> next) {
            this.prev = prev;
            this.item = item;
            this.next = next;
        }
    }

    private Node<E> first;
    private Node<E> last;
    private int size;

    void addLast(E e) {
        Node<E> n = new Node<>(last, e, null);
        if (last == null) first = n; else last.next = n;
        last = n;
        size++;
    }

    void addFirst(E e) {
        Node<E> n = new Node<>(null, e, first);
        if (first == null) last = n; else first.prev = n;
        first = n;
        size++;
    }

    E get(int index) {
        if (index < 0 || index >= size) throw new IndexOutOfBoundsException(index);
        Node<E> x;
        if (index < size / 2) {                       // closer to the front
            x = first;
            for (int i = 0; i < index; i++) x = x.next;
        } else {                                      // closer to the back
            x = last;
            for (int i = size - 1; i > index; i--) x = x.prev;
        }
        return x.item;
    }

    E removeFirst() {
        if (first == null) throw new NoSuchElementException();
        E item = first.item;
        first = first.next;
        if (first == null) last = null; else first.prev = null;
        size--;
        return item;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (Node<E> x = first; x != null; x = x.next) {
            sb.append(x.item);
            if (x.next != null) sb.append(", ");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        MiniLinkedList<String> list = new MiniLinkedList<>();
        list.addLast("B");
        list.addLast("C");
        list.addFirst("A");
        list.addLast("D");
        System.out.println(list + " get(2)=" + list.get(2));                  // [A, B, C, D] get(2)=C
        System.out.println("removed " + list.removeFirst() + " -> " + list);  // removed A -> [B, C, D]
    }
}

Time complexity of LinkedList operations

OperationTimeWhy
addFirst, addLast, offer, pushO(1)Only the end links change
removeFirst, removeLast, poll, popO(1)Only the end links change
getFirst, getLast, peekO(1)Direct first / last references
get(i), set(i, e)O(n)Walks up to n/2 nodes
add(i, e), remove(i)O(n)Walk to the node, then O(1) relink
ListIterator.add / remove / setO(1)Cursor already at the node
contains, indexOf, remove(Object)O(n)Linear scan with equals
size()O(1)Stored counter
Loop with get(i) for all iO(n²)Each get walks again — avoid
Loop with for-each / iteratorO(n)Follows next links once

ListIterator: the real strength of LinkedList

  • Once a ListIterator is positioned, add, remove, and set change the list in O(1) without shifting anything.
  • This makes LinkedList good for single-pass editing: cleaning data, inserting markers, or removing items while walking.
  • Real life: a proofreader moving through a sentence with a pen, fixing words as they go.
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class SpellFixer {
    public static void main(String[] args) {
        LinkedList<String> words = new LinkedList<>(List.of("Java", "is", "is", "esay", "to", "learn"));
        ListIterator<String> cursor = words.listIterator();

        String previous = null;
        while (cursor.hasNext()) {
            String w = cursor.next();
            if (w.equals(previous)) {
                cursor.remove();                 // drop the repeated word
                continue;
            }
            if (w.equals("esay")) {
                cursor.set("easy");              // fix spelling in place
                cursor.add("and");               // insert right after it
                cursor.add("fun");
                w = "easy";
            }
            previous = w;
        }
        System.out.println(String.join(" ", words));   // Java is easy and fun to learn
    }
}

Memory cost of LinkedList vs ArrayList

  • Every LinkedList element needs a separate Node object: an object header plus three references. On a typical 64-bit JVM with compressed references that is about 24 bytes per element, before counting the element itself.
  • ArrayList stores just one reference (about 4 bytes) per element in its array, plus up to 50% spare capacity after growth.
  • Scattered nodes also cause CPU cache misses, which is why ArrayList often beats LinkedList even for middle inserts on lists of a few thousand elements.
ElementsArrayList references (approx.)LinkedList nodes (approx.)
1,0004 to 6 KB24 KB
100,000400 to 600 KB2.4 MB
1,000,0004 to 6 MB24 MB

Differences between LinkedList and ArrayDeque

PointLinkedListArrayDeque
StructureDoubly linked nodesResizable circular array
Implements List?YesNo
Index accessYes (O(n))No
null elementsAllowedNot allowed
Speed as queue or stackGoodUsually faster
MemoryNode per elementCompact array
Remove at iteratorO(1)O(n)
Recommended for queues and stacksOnly if you need null or List methodsYes, default choice

Thread safety, null, and fail-fast behaviour

  • LinkedList is not synchronized. Wrap it with Collections.synchronizedList(new LinkedList<>()) for simple sharing, and lock on the list while iterating.
  • For concurrent queues, use ConcurrentLinkedQueue or ConcurrentLinkedDeque (lock-free), or LinkedBlockingQueue / LinkedBlockingDeque for producer-consumer work.
  • It allows null, so poll() returning null may mean "empty" or "a null element". Avoid storing nulls in queues.
  • Iterators are fail-fast: changing the list directly during a for-each throws ConcurrentModificationException. Use iterator.remove() or removeIf.

Writing your own linked list (interview favourite)

  • Interviewers usually want you to implement a linked list with your own Node class, not use java.util.LinkedList.
  • Classic problems: reverse the list, find the middle (slow and fast pointers), and detect a cycle (Floyd tortoise and hare).
  • Real life of a cycle: a broken train route where the last station points back to an earlier one, so the train never reaches the end.
public class MyLinkedList {
    static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
        }
    }

    Node head;

    void add(int value) {
        Node n = new Node(value);
        if (head == null) {
            head = n;
            return;
        }
        Node cur = head;
        while (cur.next != null) cur = cur.next;
        cur.next = n;
    }

    void reverse() {                          // O(n) time, O(1) extra space
        Node prev = null;
        Node cur = head;
        while (cur != null) {
            Node next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        head = prev;
    }

    int middle() {                            // slow moves 1 step, fast moves 2
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow.data;
    }

    boolean hasCycle() {                      // Floyd tortoise and hare
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) return true;
        }
        return false;
    }

    void print() {
        StringBuilder sb = new StringBuilder();
        for (Node c = head; c != null; c = c.next) {
            sb.append(c.data).append(c.next != null ? " -> " : "");
        }
        System.out.println(sb);
    }

    public static void main(String[] args) {
        MyLinkedList list = new MyLinkedList();
        for (int v : new int[] { 10, 20, 30, 40, 50 }) list.add(v);
        list.print();                                     // 10 -> 20 -> 30 -> 40 -> 50
        System.out.println("Middle: " + list.middle());   // 30
        list.reverse();
        list.print();                                     // 50 -> 40 -> 30 -> 20 -> 10
        System.out.println("Cycle? " + list.hasCycle());  // false
        list.head.next.next.next.next.next = list.head.next;   // node 10 now points back to 40
        System.out.println("Cycle? " + list.hasCycle());  // true
    }
}
L3

Tricky Interview Points

Q1) What is a LinkedList in Java?

Answer A doubly linked list implementation of the List and Deque interfaces in java.util. Each node stores the element and references to the previous and next nodes.

Q2) Is Java LinkedList singly or doubly linked?

Answer Doubly linked. Every node has prev and next references, and the list keeps references to both the first and last nodes.

Q3) Which interfaces does LinkedList implement?

Answer List, Deque (and therefore Queue), Cloneable, and Serializable. It does not implement RandomAccess.

Q4) What is the difference between ArrayList and LinkedList?

Answer ArrayList uses a resizable array with O(1) index access but O(n) inserts at the front. LinkedList uses nodes with O(1) operations at both ends but O(n) index access and more memory per element.

Q5) Is LinkedList.get(i) O(1)?

Answer No. It walks from the nearer end, so it is O(n) (at most n/2 steps).

Q6) Is inserting in the middle of a LinkedList O(1)?

Answer Only the relinking is O(1). Finding the position by index is O(n). It is truly O(1) only when you already have a ListIterator at that position.

Q7) Why is looping with get(i) on a LinkedList slow?

Answer Each get(i) walks from an end, so a loop over all indexes becomes O(n squared). Use for-each or an iterator, which is O(n).

Q8) Can LinkedList be used as a queue and a stack?

Answer Yes. Use offer, poll, and peek for a FIFO queue, and push, pop, and peek for a LIFO stack.

Q9) What is the difference between poll() and remove() on a LinkedList?

Answer Both remove the first element. poll() returns null when the list is empty; remove() throws NoSuchElementException.

Q10) What is the difference between peek() and element()?

Answer Both return the first element without removing it. peek() returns null when empty; element() throws NoSuchElementException.

Q11) Why is ArrayDeque preferred over LinkedList for queues?

Answer ArrayDeque uses a compact circular array with better cache locality and no per-node objects, so it is usually faster and uses less memory.

Q12) Can LinkedList contain null and duplicates?

Answer Yes, both. ArrayDeque, in contrast, does not allow null.

Q13) Does LinkedList have an initial capacity?

Answer No. It allocates one node per element, so there is no capacity or resizing.

Q14) Is LinkedList thread-safe?

Answer No. Use Collections.synchronizedList, or concurrent classes like ConcurrentLinkedDeque or LinkedBlockingDeque.

Q15) How does LinkedList find the node at index i?

Answer If i is less than size/2 it walks forward from first; otherwise it walks backward from last.

Q16) How much extra memory does a LinkedList use?

Answer Each element needs a Node object with a header and three references, typically about 24 bytes on a 64-bit JVM with compressed references, versus about 4 bytes per reference in an ArrayList.

Q17) How do you iterate a LinkedList in reverse?

Answer Use descendingIterator(), a ListIterator starting at size() moving with previous(), or reversed() in Java 21.

Q18) How do you reverse a singly linked list?

Answer Walk the list with three pointers (prev, current, next) and point each node back to the previous one. O(n) time and O(1) extra space.

Q19) How do you find the middle of a linked list in one pass?

Answer Use slow and fast pointers: slow moves one step and fast moves two. When fast reaches the end, slow is at the middle.

Q20) How do you detect a cycle in a linked list?

Answer Floyd cycle detection: move slow by one and fast by two. If they ever meet, there is a cycle; if fast reaches null, there is none.

L4

Simple Programs

Music player with next and previous

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class MusicPlayer {
    public static void main(String[] args) {
        LinkedList<String> songs = new LinkedList<>(List.of("Kesariya", "Jai Ho", "Naatu Naatu", "Kun Faya Kun"));
        ListIterator<String> player = songs.listIterator();

        String[] buttons = { "next", "next", "next", "prev", "next", "next", "next" };
        boolean forward = true;
        for (String b : buttons) {
            if (b.equals("next")) {
                if (!forward && player.hasNext()) player.next();       // skip the song we came back from
                forward = true;
                System.out.println(player.hasNext() ? "Playing " + player.next() : "End of playlist");
            } else {
                if (forward && player.hasPrevious()) player.previous();
                forward = false;
                System.out.println(player.hasPrevious() ? "Playing " + player.previous() : "Start of playlist");
            }
        }
        // Kesariya, Jai Ho, Naatu Naatu, Jai Ho, Naatu Naatu, Kun Faya Kun, End of playlist
    }
}

Text editor with undo and redo

import java.util.Deque;
import java.util.LinkedList;

public class TextEditor {
    private final StringBuilder text = new StringBuilder();
    private final Deque<String> undo = new LinkedList<>();
    private final Deque<String> redo = new LinkedList<>();

    void type(String s) {
        undo.push(text.toString());        // save the state before the change
        text.append(s);
        redo.clear();
        show("type");
    }

    void undo() {
        if (undo.isEmpty()) return;
        redo.push(text.toString());
        text.setLength(0);
        text.append(undo.pop());
        show("undo");
    }

    void redo() {
        if (redo.isEmpty()) return;
        undo.push(text.toString());
        text.setLength(0);
        text.append(redo.pop());
        show("redo");
    }

    void show(String action) {
        System.out.println(action + " -> [" + text + "]");
    }

    public static void main(String[] args) {
        TextEditor ed = new TextEditor();
        ed.type("Hello");
        ed.type(" World");
        ed.type("!!!");
        ed.undo();        // [Hello World]
        ed.undo();        // [Hello]
        ed.redo();        // [Hello World]
        ed.type(".");     // [Hello World.]  (redo history cleared)
    }
}

Office printer queue

import java.util.LinkedList;
import java.util.Queue;

public class PrinterQueue {
    record Job(String owner, String file, int pages) { }

    public static void main(String[] args) {
        Queue<Job> jobs = new LinkedList<>();
        jobs.offer(new Job("Asha", "resume.pdf", 2));
        jobs.offer(new Job("Ravi", "report.docx", 15));
        jobs.offer(new Job("Kiran", "ticket.pdf", 1));

        int minute = 0;
        while (!jobs.isEmpty()) {
            Job j = jobs.poll();
            minute += j.pages();                              // 1 page per minute
            System.out.println("Printed " + j.file() + " for " + j.owner() + " at minute " + minute);
        }
        // resume.pdf at 2, report.docx at 17, ticket.pdf at 18
    }
}

Round-robin CPU scheduling

import java.util.LinkedList;
import java.util.Queue;

public class RoundRobin {
    static class Task {
        final String name;
        int remaining;

        Task(String name, int remaining) {
            this.name = name;
            this.remaining = remaining;
        }
    }

    public static void main(String[] args) {
        Queue<Task> ready = new LinkedList<>();
        ready.offer(new Task("Chrome", 5));
        ready.offer(new Task("Spotify", 2));
        ready.offer(new Task("VS Code", 4));
        int quantum = 2;
        int clock = 0;

        while (!ready.isEmpty()) {
            Task t = ready.poll();
            int run = Math.min(quantum, t.remaining);
            clock += run;
            t.remaining -= run;
            if (t.remaining > 0) {
                ready.offer(t);                               // back of the line
                System.out.println(clock + "ms: " + t.name + " paused, " + t.remaining + " left");
            } else {
                System.out.println(clock + "ms: " + t.name + " finished");
            }
        }
        // 2ms Chrome paused, 4ms Spotify finished, 6ms VS Code paused,
        // 8ms Chrome paused, 10ms VS Code finished, 11ms Chrome finished
    }
}

Recently viewed products

import java.util.LinkedList;

public class RecentlyViewed {
    private final LinkedList<String> items = new LinkedList<>();
    private final int limit;

    RecentlyViewed(int limit) {
        this.limit = limit;
    }

    void view(String product) {
        items.remove(product);                       // already viewed? move it to the front
        items.addFirst(product);
        if (items.size() > limit) items.removeLast();   // forget the oldest
        System.out.println("Viewed " + product + " -> " + items);
    }

    public static void main(String[] args) {
        RecentlyViewed recent = new RecentlyViewed(3);
        recent.view("Phone");
        recent.view("Shoes");
        recent.view("Watch");
        recent.view("Phone");     // [Phone, Watch, Shoes]
        recent.view("Laptop");    // [Laptop, Phone, Watch]  (Shoes dropped)
    }
}

Merge two sorted linked lists

public class MergeSortedLists {
    static class Node {
        int val;
        Node next;

        Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    static Node merge(Node a, Node b) {
        Node dummy = new Node(0, null);
        Node tail = dummy;
        while (a != null && b != null) {
            if (a.val <= b.val) {
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }
        tail.next = (a != null) ? a : b;
        return dummy.next;
    }

    static Node of(int... values) {
        Node head = null;
        for (int i = values.length - 1; i >= 0; i--) head = new Node(values[i], head);
        return head;
    }

    public static void main(String[] args) {
        Node hallA = of(101, 105, 110);           // roll numbers from exam hall A
        Node hallB = of(102, 103, 120);           // roll numbers from exam hall B
        StringBuilder sb = new StringBuilder();
        for (Node n = merge(hallA, hallB); n != null; n = n.next) {
            sb.append(n.val).append(' ');
        }
        System.out.println(sb.toString().trim()); // 101 102 103 105 110 120
    }
}

Pass the parcel game (Josephus problem)

import java.util.LinkedList;
import java.util.List;

public class PassTheParcel {
    public static void main(String[] args) {
        LinkedList<String> circle = new LinkedList<>(List.of("Asha", "Ravi", "Kiran", "Meena", "John"));
        int k = 3;                                        // music stops on every 3rd person

        while (circle.size() > 1) {
            for (int i = 1; i < k; i++) {
                circle.addLast(circle.removeFirst());     // pass the parcel along
            }
            System.out.println(circle.removeFirst() + " is out");
        }
        System.out.println("Winner: " + circle.getFirst());
        // Kiran, Asha, John, Ravi are out; Winner: Meena
    }
}
L5

Problem Solving Tricks

  • LinkedList = List + Deque: one class can be a list, queue, stack, or deque.
  • Ends are O(1); index access is O(n). Never loop with get(i) on a LinkedList.
  • Use for-each, an Iterator, or descendingIterator() to traverse.
  • Use ListIterator.add / remove / set for O(1) edits while walking.
  • Prefer poll / peek / offer over remove / element / add when the list may be empty.
  • For pure queues and stacks, ArrayDeque is usually faster; use LinkedList if you need null or List methods.
  • Not sure which list? Start with ArrayList and measure before switching.
  • Declare by role: Queue<T> q = new LinkedList<>() or Deque<T> stack = new LinkedList<>().
  • Middle insert is O(1) only when you already stand at that node with an iterator.
  • In interviews, write your own Node class for reverse, middle, merge, and cycle problems.
L6

Practice Programs List

  1. Create a LinkedList of 5 cities and use addFirst, addLast, removeFirst, and removeLast.
  2. Print a LinkedList forward with for-each and backward with descendingIterator().
  3. Use a LinkedList as a queue for a bank token system with offer, peek, and poll.
  4. Use a LinkedList as a stack to reverse a word with push and pop.
  5. Check whether a sentence is a palindrome using pollFirst and pollLast.
  6. Show the difference between poll() and remove() on an empty LinkedList.
  7. Insert a new metro stop after "Begumpet" using a ListIterator.
  8. Time 50,000 addFirst calls on LinkedList vs add(0, e) on ArrayList.
  9. Time a get(i) loop on LinkedList vs a for-each loop and explain the difference.
  10. Build a "recently viewed" list that keeps only the last 3 products.
  11. Simulate round-robin scheduling of 4 tasks with a time quantum of 3.
  12. Write your own singly linked list with add, print, and reverse.
  13. Find the middle node in one pass using slow and fast pointers.
  14. Detect a cycle in your linked list using Floyd algorithm.