Algorithm:
Rust implementation:
use std::mem;
struct Stack {
head: Link
}
struct Node {
value: i32,
next: Link,
}
enum Link {
Empty,
Some(Box<Node>),
}
impl Stack {
fn new() -> Self {
Stack { head: Link::Empty }
}
fn push(&mut self, value: i32) {
let node = Node {value, next: mem::replace(&mut self.head, Link::Empty)};
self.head = Link::Some(Box::new(node));
}
fn pop(&mut self) -> Option<i32> {
match mem::replace(&mut self.head, Link::Empty) {
Link::Empty => None,
Link::Some(boxed_node) => {
self.head = boxed_node.next;
Some(boxed_node.value)
}
}
}
}