Which problem does a linked list solve better than a simple 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.
Which limitation of arrays is addressed by using linked lists?
Think about what happens when you want to add more elements than an array can hold.
Arrays have a fixed size set at creation, so resizing requires creating a new array. Linked lists can grow or shrink by adding or removing nodes without resizing.
What is the printed output after inserting nodes in this Rust linked list?
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct LinkedList {
head: Option<Box<Node>>,
}
impl LinkedList {
fn new() -> Self {
LinkedList { head: None }
}
fn insert_front(&mut self, val: i32) {
let new_node = Box::new(Node {
value: val,
next: self.head.take(),
});
self.head = Some(new_node);
}
fn print_list(&self) {
let mut current = &self.head;
while let Some(node) = current {
print!("{} -> ", node.value);
current = &node.next;
}
print!("null\n");
}
}
fn main() {
let mut list = LinkedList::new();
list.insert_front(10);
list.insert_front(20);
list.insert_front(30);
list.print_list();
}New nodes are added at the front, so the last inserted node appears first.
Each new node is inserted at the front, so the list order is last inserted to first inserted: 30, then 20, then 10.
What is the output after deleting the first node from this linked list?
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct LinkedList {
head: Option<Box<Node>>,
}
impl LinkedList {
fn new() -> Self {
LinkedList { head: None }
}
fn insert_front(&mut self, val: i32) {
let new_node = Box::new(Node {
value: val,
next: self.head.take(),
});
self.head = Some(new_node);
}
fn delete_front(&mut self) {
if let Some(node) = self.head.take() {
self.head = node.next;
}
}
fn print_list(&self) {
let mut current = &self.head;
while let Some(node) = current {
print!("{} -> ", node.value);
current = &node.next;
}
print!("null\n");
}
}
fn main() {
let mut list = LinkedList::new();
list.insert_front(1);
list.insert_front(2);
list.insert_front(3);
list.delete_front();
list.print_list();
}Deleting the front removes the first inserted node at the head.
Initially, nodes are 3 -> 2 -> 1 -> null. Deleting front removes 3, so list becomes 2 -> 1 -> null.
Which of the following is a disadvantage of linked lists compared to arrays?
Think about what extra information each node in a linked list must store.
Each node in a linked list stores a pointer to the next node, which uses extra memory compared to arrays that store only data.
