A Linked List is a linear data structure where elements are stored in nodes, and each node points to the next node in the sequence. Unlike arrays, linked lists do not have a fixed size and can grow or shrink dynamically. This makes them efficient for insertions and deletions, but slower for direct access to an element.
function insertAtHead(value):
node = new Node(value)
node.next = head.next
head.next = node
function insertAtTail(value):
node = new Node(value)
cur = head
while cur.next is not null:
cur = cur.next
cur.next = node
function insertAt(index, value):
if index == 0:
insertAtHead(value)
return
cur = head
for i = 1 to index:
if cur.next is null: break
cur = cur.next
node = new Node(value)
node.next = cur.next
cur.next = node
function deleteAt(index):
cur = head
prev = null
for i = 0 to index:
prev = cur
cur = cur.next
prev.next = cur.next
Arrays store elements in contiguous memory blocks, enabling O(1) index access and excellent CPU spatial cache prefetching. Linked list nodes are allocated dynamically across heap memory, leading to memory fragmentation and frequent CPU cache misses.
Maintain three pointers: prev (initialized to null), curr (head), and next. Iterate through the list:
let prev = null, cur = head;
while (cur) {
let next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
head = prev;Use two pointers: slow moving 1 step at a time, and fast moving 2 steps at a time. If the list has a cycle, fast will eventually catch up and meet slow inside the loop. If fast reaches null, no cycle exists.
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true; // Cycle detected
}
return false;Sign in to join the discussion
Hand-picked resources to deepen your understanding
© 2025 See Algorithms. Code licensed under MIT, content under CC BY-NC 4.0