You need to store a collection of items where insertions happen frequently at the beginning and middle of the collection. Which data structure is generally better to use?
Think about what happens when you insert elements in the middle of an array versus a linked list.
Linked lists allow insertions and deletions at any position efficiently because they only change pointers, while arrays require shifting elements which is costly.
Consider the following C++ code simulating access times for array and linked list. What is the printed output?
int arr[3] = {10, 20, 30}; struct Node { int val; Node* next; }; Node n3 = {30, nullptr}; Node n2 = {20, &n3}; Node n1 = {10, &n2}; std::cout << arr[1] << " " << n1.next->val << std::endl;
Check the index used for array and the pointer navigation in linked list.
arr[1] accesses the second element which is 20. n1.next points to n2 which has value 20.
What is the state of the linked list after the following operations?
struct Node {
int val;
Node* next;
};
Node* head = new Node{1, nullptr};
head->next = new Node{3, nullptr};
Node* newNode = new Node{2, nullptr};
newNode->next = head->next;
head->next = newNode;
// Print list
Node* curr = head;
while(curr) {
std::cout << curr->val << " -> ";
curr = curr->next;
}
std::cout << "null" << std::endl;Trace the pointer changes step by step.
The new node with value 2 is inserted between 1 and 3, so the list becomes 1 -> 2 -> 3 -> null.
Which statement correctly describes the memory usage difference between arrays and linked lists?
Consider what extra information each linked list node stores compared to array elements.
Each linked list node stores the data plus a pointer to the next node, increasing memory usage compared to arrays which store only data.
You are designing a real-time system that requires a queue with frequent deletions from the front and occasional insertions at the back. Which data structure is most suitable and why?
Think about what happens when deleting elements from the front in arrays versus linked lists.
Linked lists allow efficient deletions from the front by moving the head pointer, while arrays require shifting all elements which is costly.
