Imagine you have a list of items that can grow or shrink often. Which problem does a linked list solve better than an array?
Think about what happens when you add or remove items in the middle of an array.
Arrays require shifting elements when inserting or deleting in the middle, which is slow. Linked lists use pointers to connect nodes, so insertion and deletion are fast without shifting.
What is the output after inserting a new node with value 99 at the start of the linked list?
Compare it with inserting 99 at the start of an array.
struct Node {
int data;
Node* next;
};
Node* head = new Node{1, new Node{2, new Node{3, nullptr}}};
// Insert 99 at start
Node* newNode = new Node{99, head};
head = newNode;
// Print linked list
Node* temp = head;
while(temp != nullptr) {
std::cout << temp->data << " -> ";
temp = temp->next;
}
std::cout << "null";
// Array insertion (conceptual)
// int arr[] = {1, 2, 3};
// Insert 99 at start requires shifting elementsFocus on how the new node points to the old head.
The new node with value 99 becomes the new head and points to the old list. The print shows 99 first, then 1, 2, 3, ending with null.
Look at this code snippet that tries to insert a node at the end of a linked list. What problem will it cause?
struct Node {
int data;
Node* next;
};
void insertEnd(Node* head, int val) {
Node* newNode = new Node{val, nullptr};
Node* temp = head;
while(temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode; // Fixed here
}
// Usage:
Node* head = new Node{1, nullptr};
insertEnd(head, 2);Check what happens when you assign temp = newNode inside the loop.
Assigning temp = newNode only changes the local pointer temp, not the last node's next pointer. So the list remains unchanged and the new node is not linked.
Given this linked list and code to delete the first node, what is printed?
struct Node {
int data;
Node* next;
};
Node* head = new Node{10, new Node{20, new Node{30, nullptr}}};
// Delete first node
Node* temp = head;
head = head->next;
delete temp;
// Print list
Node* curr = head;
while(curr != nullptr) {
std::cout << curr->data << " -> ";
curr = curr->next;
}
std::cout << "null";Think about what happens to the head pointer after deletion.
Deleting the first node moves head to the second node. The list now starts at 20 and continues to 30, ending with null.
Which reason best explains why linked lists are preferred over arrays when memory usage is unpredictable?
Think about how arrays and linked lists allocate memory differently.
Arrays require a large block of continuous memory, which can be hard to find if size is unknown. Linked lists allocate memory node by node, so they handle dynamic sizes better.
