📖 Scenario: Imagine you are building a simple system to manage a stack of books. You want to add and remove books in a last-in, first-out order. To do this efficiently, you will use a linked list to implement the stack.
🎯 Goal: Build a stack data structure using a linked list in Rust. You will create the linked list nodes, manage the stack operations, and finally print the stack contents.
📋 What You'll Learn
Create a linked list node struct called Node with a value field of type i32 and a next field as an Option>.
Create a struct called Stack with a top field as an Option>.
Implement a method push for Stack to add a new value on top of the stack.
Implement a method pop for Stack to remove and return the top value from the stack.
Implement a method print_stack for Stack to print all values from top to bottom.
Use the stack to push the values 10, 20, and 30 in that order.
Pop one value from the stack.
Print the current stack contents.
💡 Why This Matters
🌍 Real World
Stacks are used in many real-world applications like undo features in text editors, browser history, and expression evaluation.
💼 Career
Understanding stack implementation helps in software development roles that require knowledge of data structures and memory management.
Progress0 / 4 steps
1
Create the Node struct for the linked list
Create a struct called Node with a field value of type i32 and a field next of type Option>.
DSA Rust
Hint
Use struct Node with two fields: value and next. The next field should be an Option wrapping a Box pointing to another Node.
2
Create the Stack struct with a top pointer
Create a struct called Stack with a field top of type Option> to represent the top of the stack.
DSA Rust
Hint
The Stack struct needs a top field that points to the top Node or None if empty.
3
Implement push and pop methods for Stack
Implement an impl Stack block with two methods: push(&mut self, value: i32) to add a new node on top, and pop(&mut self) -> Option to remove and return the top value.
DSA Rust
Hint
Use self.top.take() to temporarily take ownership of the top node. For push, create a new node pointing to the old top. For pop, update top to the next node and return the popped value.
4
Use the stack and print its contents
Create a main function. Inside it, create a mutable Stack with top set to None. Push the values 10, 20, and 30 in that order. Then pop one value. Finally, print the remaining stack values from top to bottom using a print_stack method you will add.
DSA Rust
Hint
Define a print_stack method that walks through the linked list from top and prints each value followed by an arrow. In main, push 10, 20, 30, pop once, then print the stack.
Practice
(1/5)
1. What is the main advantage of implementing a stack using a linked list instead of an array?
easy
A. It allows random access to elements
B. It uses less memory than an array
C. The stack can grow dynamically without a fixed size limit
D. It is easier to sort the stack elements
Solution
Step 1: Understand stack size limitation in arrays
Arrays have fixed size, so stacks implemented with arrays have a maximum capacity.
Step 2: Linked list dynamic size property
Linked lists can grow or shrink dynamically by adding or removing nodes, so stack size is not fixed.
Final Answer:
The stack can grow dynamically without a fixed size limit -> Option C
Quick Check:
Dynamic size = Advantage of linked list stack [OK]
Hint: Linked list stacks grow dynamically, arrays don't [OK]
Common Mistakes:
Thinking linked list uses less memory always
Confusing stack with queue behavior
Assuming random access is possible in linked list
2. Which of the following Rust code snippets correctly defines a node struct for a linked list stack?
easy
A. struct Node { data: i32, next: Option }
B. struct Node { data: i32, next: Node }
C. struct Node { data: i32, next: &Node }
D. struct Node { data: i32, next: Box<Node> }
Solution
Step 1: Understand Rust ownership and recursive types
Recursive types like linked lists require indirection using Box and Option for nullable pointers.
Step 2: Analyze each option
struct Node { data: i32, next: Option } uses Option which allows nullable next pointer; struct Node { data: i32, next: Node } and struct Node { data: i32, next: &Node } are invalid due to recursive type without indirection; struct Node { data: i32, next: Box<Node> } misses Option, so no null pointer.
3. Consider the following Rust code for pushing elements onto a linked list stack:
struct Node {
data: i32,
next: Option,
}
struct Stack {
head: Option,
}
impl Stack {
fn push(&mut self, val: i32) {
let new_node = Box::new(Node { data: val, next: self.head.take() });
self.head = Some(new_node);
}
}
fn main() {
let mut stack = Stack { head: None };
stack.push(10);
stack.push(20);
stack.push(30);
// What is the top element's data now?
println!("{}", stack.head.as_ref().unwrap().data);
}
medium
A. 30
B. 20
C. 10
D. None
Solution
Step 1: Trace push operations
Push 10: head points to node with data 10; Push 20: head points to node with data 20, next is 10; Push 30: head points to node with data 30, next is 20.
Step 2: Identify top element
After pushes, top element is the head node's data, which is 30.
Final Answer:
30 -> Option A
Quick Check:
Last pushed = top element = 30 [OK]
Hint: Top is last pushed element in stack [OK]
Common Mistakes:
Confusing order of nodes in linked list
Assuming head points to bottom element
Not using take() causing borrow errors
4. The following Rust code for popping an element from a linked list stack has an error. What is the error?
D. Using unwrap() on Option without handling ownership
Solution
Step 1: Analyze unwrap() usage on self.head
unwrap() consumes the Option, but self.head is borrowed mutably, causing ownership error.
Step 2: Correct way is to use take() to move ownership
Using self.head.take() moves ownership out safely, allowing access to node and updating head.
Final Answer:
Using unwrap() on Option without handling ownership -> Option D
Quick Check:
unwrap() consumes Option, use take() instead [OK]
Hint: Use take() to move Option ownership safely [OK]
Common Mistakes:
Using unwrap() causing borrow checker errors
Ignoring empty stack check
Confusing references and ownership
5. You want to implement a function reverse_stack that reverses the elements of a linked list stack without using extra data structures. Which approach correctly achieves this in Rust?
hard
A. Iteratively pop elements and push them onto a new stack, then replace original stack
B. Recursively pop elements, reverse the rest, then push popped element back
C. Traverse linked list and swap data values between nodes from head to tail
D. Use a vector to collect elements, reverse vector, then rebuild stack
Solution
Step 1: Understand constraints - no extra data structures allowed
Options A and D use extra stacks or vectors, so they violate constraints.
Step 2: Recursive approach explanation
Recursively pop elements until stack is empty, then push elements back in reverse order, effectively reversing stack without extra storage.
Step 3: Swapping data values is complex and error-prone
Traverse linked list and swap data values between nodes from head to tail requires traversal and swapping data, which is complicated and not idiomatic in Rust linked lists.
Final Answer:
Recursively pop elements, reverse the rest, then push popped element back -> Option B
Quick Check:
Recursion reverses stack without extra structures [OK]
Hint: Use recursion to reverse stack without extra storage [OK]
Common Mistakes:
Using extra data structures despite constraints
Trying to swap node data directly
Ignoring ownership rules in recursion
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.