1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Singly Linked List
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Singly Linked List

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
10Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Singly Linked List

Overview

A Singly Linked List is a linear data structure consisting of a sequence of nodes. Unlike an array where elements are stored in contiguous memory locations, linked list nodes can be scattered anywhere in memory. Each node contains two things: the data it holds, and a pointer (or reference) to the next node in the sequence.

The primary advantage of a linked list over an array is dynamic size and O(1) insertions/deletions at the head (or anywhere, provided you already have a reference to the specific node). In an array, inserting an element at the beginning requires shifting every single subsequent element to the right, which is an O(N) operation. In a linked list, you simply update a couple of pointers.

However, this comes at the cost of random access. You cannot instantly access the 5th element like you can in an array (arr[4]). To find the 5th element in a linked list, you must start at the head and traverse node by node (O(N) time complexity). Additionally, the pointers themselves consume extra memory overhead.

Syntax

Notice how insertAtHead requires zero data shifting. No matter how large the list gets, inserting at the front is always exactly two pointer assignments.

Node Definition and Basic Traversal
java
public class LinkedList {
    // 1. Defining the Node class (usually a static inner class)
    static class Node {
        int data;
        Node next;
        
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    
    Node head; // Pointer to the first node
    
    // 2. O(1) Insertion at the Head
    public void insertAtHead(int data) {
        Node newNode = new Node(data);
        newNode.next = head; // Point new node to current head
        head = newNode;      // Make new node the new head
    }
    
    // 3. O(N) Traversal
    public void printList() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " -> ");
            current = current.next; // Move to the next node
        }
        System.out.println("null");
    }
    
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.insertAtHead(3);
        list.insertAtHead(2);
        list.insertAtHead(1);
        list.printList(); // Output: 1 -> 2 -> 3 -> null
    }
}

Common Pitfalls

  • Losing the head pointer. When traversing a linked list, NEVER use head = head.next unless you are permanently deleting the head node. If you overwrite the head pointer, you lose reference to the beginning of the list, and the Garbage Collector will destroy your data. Always create a temporary pointer: Node current = head;.
  • NullPointerException on edge cases. When inserting or deleting, always ask yourself: 'What if the list is empty (head == null)?' or 'What if I am deleting the very last node?'. Failing to handle the empty-list condition is the #1 cause of bugs in linked list code.
  • Forgetting to update the next pointer of the preceding node during deletion. To delete a node, you must have a reference to the node before it, so you can route its next pointer around the deleted node to the one after it.

Interview Questions

What is the time complexity of accessing the middle element of a Singly Linked List?

O(N). Because memory is not contiguous, there is no index-based math to find the middle. You must start at the head and traverse node-by-node until you reach the middle.

How do you reverse a Singly Linked List in place?

You need three pointers: prev (initially null), current (initially head), and nextTemp. In a loop, store current.next in nextTemp, change current.next to point to prev, then move prev and current one step forward. Return prev as the new head.

Why might a Linked List be preferred over a dynamically resizing array (like ArrayList) for building a Queue?

A Queue requires constant insertions at one end and deletions at the other. In an ArrayList, removing from the front (dequeue) requires shifting all remaining elements left, an O(N) operation. A Linked List can enqueue at the tail and dequeue at the head in strict O(1) time with no resizing overhead.

Real-World Example

Operating systems use linked lists to manage free memory blocks. When a program requests memory, the OS traverses a linked list of free blocks to find one large enough. When memory is freed, it is inserted back into the list. Linked lists are perfect here because insertions and deletions happen constantly and unpredictably.

example
java
// A simplified Free Memory Manager
class MemoryBlock {
    int size;
    int startAddress;
    MemoryBlock next;
}

public class MemoryAllocator {
    MemoryBlock freeListHead;
    
    public void freeMemory(int size, int address) {
        // O(1) insertion of newly freed memory back into the pool
        MemoryBlock newFreeBlock = new MemoryBlock(size, address);
        newFreeBlock.next = freeListHead;
        freeListHead = newFreeBlock;
    }
}

Check Your Knowledge

Test your understanding of Singly Linked List with these quick questions.

Question 1

Which operation is O(N) in a Singly Linked List?

Question 2

What does every node in a Singly Linked List contain?

Question 3

What happens if you accidentally write `head = head.next` while trying to traverse and print the list?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Singly Linked List

Overview

A Singly Linked List is a linear data structure consisting of a sequence of nodes. Unlike an array where elements are stored in contiguous memory locations, linked list nodes can be scattered anywhere in memory. Each node contains two things: the data it holds, and a pointer (or reference) to the next node in the sequence.

The primary advantage of a linked list over an array is dynamic size and O(1) insertions/deletions at the head (or anywhere, provided you already have a reference to the specific node). In an array, inserting an element at the beginning requires shifting every single subsequent element to the right, which is an O(N) operation. In a linked list, you simply update a couple of pointers.

However, this comes at the cost of random access. You cannot instantly access the 5th element like you can in an array (arr[4]). To find the 5th element in a linked list, you must start at the head and traverse node by node (O(N) time complexity). Additionally, the pointers themselves consume extra memory overhead.

Syntax

Notice how insertAtHead requires zero data shifting. No matter how large the list gets, inserting at the front is always exactly two pointer assignments.

Node Definition and Basic Traversal
java
public class LinkedList {
    // 1. Defining the Node class (usually a static inner class)
    static class Node {
        int data;
        Node next;
        
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    
    Node head; // Pointer to the first node
    
    // 2. O(1) Insertion at the Head
    public void insertAtHead(int data) {
        Node newNode = new Node(data);
        newNode.next = head; // Point new node to current head
        head = newNode;      // Make new node the new head
    }
    
    // 3. O(N) Traversal
    public void printList() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " -> ");
            current = current.next; // Move to the next node
        }
        System.out.println("null");
    }
    
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.insertAtHead(3);
        list.insertAtHead(2);
        list.insertAtHead(1);
        list.printList(); // Output: 1 -> 2 -> 3 -> null
    }
}

Common Pitfalls

  • Losing the head pointer. When traversing a linked list, NEVER use head = head.next unless you are permanently deleting the head node. If you overwrite the head pointer, you lose reference to the beginning of the list, and the Garbage Collector will destroy your data. Always create a temporary pointer: Node current = head;.
  • NullPointerException on edge cases. When inserting or deleting, always ask yourself: 'What if the list is empty (head == null)?' or 'What if I am deleting the very last node?'. Failing to handle the empty-list condition is the #1 cause of bugs in linked list code.
  • Forgetting to update the next pointer of the preceding node during deletion. To delete a node, you must have a reference to the node before it, so you can route its next pointer around the deleted node to the one after it.

Interview Questions

What is the time complexity of accessing the middle element of a Singly Linked List?

O(N). Because memory is not contiguous, there is no index-based math to find the middle. You must start at the head and traverse node-by-node until you reach the middle.

How do you reverse a Singly Linked List in place?

You need three pointers: prev (initially null), current (initially head), and nextTemp. In a loop, store current.next in nextTemp, change current.next to point to prev, then move prev and current one step forward. Return prev as the new head.

Why might a Linked List be preferred over a dynamically resizing array (like ArrayList) for building a Queue?

A Queue requires constant insertions at one end and deletions at the other. In an ArrayList, removing from the front (dequeue) requires shifting all remaining elements left, an O(N) operation. A Linked List can enqueue at the tail and dequeue at the head in strict O(1) time with no resizing overhead.

Real-World Example

Operating systems use linked lists to manage free memory blocks. When a program requests memory, the OS traverses a linked list of free blocks to find one large enough. When memory is freed, it is inserted back into the list. Linked lists are perfect here because insertions and deletions happen constantly and unpredictably.

example
java
// A simplified Free Memory Manager
class MemoryBlock {
    int size;
    int startAddress;
    MemoryBlock next;
}

public class MemoryAllocator {
    MemoryBlock freeListHead;
    
    public void freeMemory(int size, int address) {
        // O(1) insertion of newly freed memory back into the pool
        MemoryBlock newFreeBlock = new MemoryBlock(size, address);
        newFreeBlock.next = freeListHead;
        freeListHead = newFreeBlock;
    }
}

Check Your Knowledge

Test your understanding of Singly Linked List with these quick questions.

Question 1

Which operation is O(N) in a Singly Linked List?

Question 2

What does every node in a Singly Linked List contain?

Question 3

What happens if you accidentally write `head = head.next` while trying to traverse and print the list?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A