Which scenario best shows when a linked list is a better choice than an array?
Think about which data structure handles insertions and deletions in the middle efficiently.
Linked lists allow quick insertions and deletions anywhere because they only change pointers, unlike arrays which require shifting elements.
What is the output after inserting 99 at index 1 in both an array and a linked list?
use std::collections::LinkedList;
fn main() {
let mut arr = vec![1, 2, 3];
arr.insert(1, 99);
// Linked list insertion simulation
let mut list = LinkedList::new();
list.push_back(1);
list.push_back(2);
list.push_back(3);
// Insert 99 before second element
let mut cursor = list.cursor_front_mut();
cursor.move_next();
cursor.insert_before(99);
println!("Array: {:?}", arr);
print!("LinkedList: ");
for val in list.iter() {
print!("{} ", val);
}
}Check where the new element 99 is inserted in both structures.
Inserting 99 at index 1 in the array shifts elements right. In the linked list, inserting before the second element places 99 after the first.
Consider this Rust code that tries to remove the last element from a linked list. Why does it cause a runtime panic?
use std::collections::LinkedList;
fn main() {
let mut list = LinkedList::new();
list.push_back(10);
list.push_back(20);
list.pop_back();
list.pop_back();
list.pop_back().unwrap(); // Causes panic here
}What happens if you call pop_back() on an empty list?
pop_back() returns an Option. Calling it on an empty list returns None. If code assumes Some value without checking, it can panic.
What is the main difference in memory layout between an array and a linked list?
Choose the option that best describes it.
Think about how arrays and linked lists organize their elements in memory.
Arrays store elements next to each other in memory, which helps fast access by index. Linked lists store nodes anywhere in memory, linked by pointers.
You need to design a system that requires both fast random access by index and frequent insertions/deletions in the middle of the collection. Which data structure or approach is best?
Think about data structures that combine benefits of arrays and linked lists.
Balanced trees or skip lists provide near-logarithmic time for both random access and insertions/deletions, balancing the trade-offs of arrays and linked lists.
