This lesson includes an expert video walkthrough — purchase once for a full year of unlimited replays to master every key point 🎬
Linked List
Knowledge Summary
Definition of a Linked List
A linked list is a linear data structure made up of a sequence of nodes. Each node contains:
- A data field: stores data
- A pointer field: stores the address of the next node
Linked Lists vs Arrays
| Property | Array | Linked List |
|---|---|---|
| Memory layout | Contiguous | Non-contiguous |
| Accessing the i-th element | O(1) | O(n) |
| Insertion / deletion | O(n) | O(1) (when the position is known) |
| Space | Fixed size | Dynamically allocated |
Types of Linked Lists
- Singly linked list: each node has only one
nextpointer - Doubly linked list: each node has both
prevandnextpointers - Circular linked list: the
nextpointer of the tail points to the head
Basic Operations on a Linked List
1struct Node {
2 int data;
3 Node* next;
4};
5
6// Head insertion
7void insertHead(Node*& head, int val) {
8 Node* newNode = new Node{val, head};
9 head = newNode;
10}
11
12// Delete a node
13void deleteNode(Node*& head, int val) {
14 if (!head) return;
15 if (head->data == val) {
16 Node* temp = head;
17 head = head->next;
18 delete temp;
19 return;
20 }
21 Node* cur = head;
22 while (cur->next && cur->next->data != val)
23 cur = cur->next;
24 if (cur->next) {
25 Node* temp = cur->next;
26 cur->next = temp->next;
27 delete temp;
28 }
29}Common Preliminary-Round Question Types
- How pointers change after insertion or deletion in a linked list
- Given a sequence of operations, determine the final state of the linked list
- Analyze the steps for reversing a singly linked list