Singly Linked List
A linear data structure where each element (node) contains a value and a reference to the next node in the sequence.Overview
Singly linked lists provide efficient insertion and deletion at the head (O(1)) but require O(n) time for access to arbitrary positions. Perfect for scenarios with frequent insertions and deletions.Implementation
Node Structure
Class Definition
API Reference
push(value: T): void
Adds an element to the end of the linked list.insert(value: T, index: number): void
Inserts a new element at the specified position.value: The value to insertindex: Position to insert at (0-based)
- Insert at head: O(1)
- Insert at tail: O(n)
- Insert at arbitrary position: O(n)
pop(): Node<T> | null
Removes and returns the last element from the linked list.at(index: number): Node<T> | null
Returns the element at the given index without removing it.remove(value: T): void
Removes the first occurrence of an element from the list.removeAt(index: number): void
Removes an element from the specified position in the list.isEmpty(): boolean
Returns true if the list is empty, false otherwise.toString(): string
Returns a string representation of the list.Problems & Solutions
Problem 1: Partition List
Partition a linked list around a value x, such that all nodes less than x come before nodes greater than or equal to x.Problem 2: Add Two Numbers
Add two numbers represented by linked lists, where each node contains a single digit stored in reverse order.Complexity Summary
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| push | O(n) | O(1) |
| insert (head) | O(1) | O(1) |
| insert (tail) | O(n) | O(1) |
| insert (arbitrary) | O(n) | O(1) |
| pop | O(n) | O(1) |
| at | O(n) | O(1) |
| remove | O(n) | O(1) |
| removeAt | O(n) | O(1) |
| isEmpty | O(1) | O(1) |
| toString | O(n) | O(1) |
Key Characteristics
Advantages:
- Dynamic size
- Efficient insertion/deletion at head (O(1))
- No memory waste
- Easy to implement
Use Cases
- Stack implementation: Fast push/pop at head
- Queue implementation: When combined with tail pointer
- Dynamic memory allocation: When size is unknown
- Undo functionality: Storing state history
Related Data Structures
Doubly Linked List
Bidirectional traversal support
Stack
Built using singly linked list
Queue
Built using singly linked list