Write a stack on a singly linked list of Option<Box<Node>> links
Stack keeps its items in a singly linked list: each Node owns the next one through an Option<Box<Node>>. Write push and pop. Then explain in two or three sentences why a doubly linked list cannot be built from the same kind of links.
Requirements:
pushandpopwork at the head in O(1);popon an empty stack returnsNone.- No
unsafe, noRc, nocloneof nodes; keep the struct definitions as they are. mainstays as it is and printsSome(3) Some(2).
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct Stack {
head: Option<Box<Node>>,
}
impl Stack {
fn push(&mut self, value: i32) {
// your code here
}
fn pop(&mut self) -> Option<i32> {
// your code here
}
}
fn main() {
let mut s = Stack { head: None };
s.push(1);
s.push(2);
s.push(3);
println!("{:?} {:?}", s.pop(), s.pop());
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
push takes the old head with take() and makes it the new node's next; pop takes the head, moves its next into head and returns the value, both O(1). A doubly linked node has two owners: Rc forward plus Weak back, or unsafe.
- Moving
self.headout of&mut selfwithouttake(), which fails with E0507 - Walking to the tail on every push and losing the O(1) cost
- Adding a
prev: Option<Box<Node>>field, as if aBoxcould have two owners
- Why can dropping a very long
Boxlist overflow the stack, and how would a hand-writtenDropfix it? - How would
Rcforward links andWeakback links make a doubly linked list work?
The head cannot simply be moved out of &mut self: that would leave a hole in its place. Option::take takes the value and leaves None, so the struct stays whole at every moment:
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct Stack {
head: Option<Box<Node>>,
}
impl Stack {
fn push(&mut self, value: i32) {
let next = self.head.take();
self.head = Some(Box::new(Node { value, next }));
}
fn pop(&mut self) -> Option<i32> {
self.head.take().map(|node| {
self.head = node.next;
node.value
})
}
}
fn main() {
let mut s = Stack { head: None };
s.push(1);
s.push(2);
s.push(3);
println!("{:?} {:?}", s.pop(), s.pop()); // Some(3) Some(2)
}push allocates one node and moves a pointer; pop moves the node's Box into the closure, hands next to head and returns the value — both operations are O(1). An empty stack yields None on its own: take() returned None, and map called nothing. Writing next: self.head would not compile: error[E0507]: cannot move out of `self.head` which is behind a mutable reference.
A Box is the only owner, so Option<Box<Node>> builds only a chain where each node has one predecessor. In a doubly linked list both neighbors point at a node, while it can have only one owner. The usual answer is Rc<RefCell<Node>> forward and Weak<RefCell<Node>> back, so no Rc cycle forms; the standard LinkedList is written with raw pointers inside unsafe. In C++ or Java such a list takes two plain pointers, because there the compiler does not track ownership.