A linked list is a linear data structure made of nodes, where each node holds a value and a reference (pointer) to the next node. Unlike arrays, elements aren't stored contiguously in memory, which makes insertion and deletion at arbitrary positions much cheaper — at the cost of O(n) random access.
next node. Simple and memory-efficient, but traversal is one-directional.next and prev pointers, allowing traversal in both directions at the cost of extra memory per node.null, useful for round-robin scheduling and buffering.prev, curr, next) without extra space.| Operation | Array | Linked List |
|---|---|---|
| Access by index | O(1) | O(n) |
| Search | O(n) | O(n) |
| Insert at head | O(n) | O(1) |
| Insert/delete at known node | O(n) | O(1) |
| Space overhead | O(n) | O(n) + pointer per node |
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 1. Detect a cycle using fast & slow pointers (Floyd's algorithm)
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# 2. Find the middle node using fast & slow pointers
def middle_node(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
# 3. Merge two sorted linked lists using a dummy head
def merge_two_lists(l1, l2):
dummy = ListNode()
tail = dummy
while l1 and l2:
if l1.val <= l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
tail.next = l1 if l1 else l2
return dummy.next
You want to detect whether a linked list contains a cycle without using extra space. Which technique is best suited?
Once you're comfortable with the concepts above, try solving these problems to reinforce your understanding: