use Option
This commit is contained in:
parent
71587e810c
commit
eca0964be5
1 changed files with 7 additions and 11 deletions
18
src/main.rs
18
src/main.rs
|
|
@ -13,11 +13,7 @@ pub struct List<T> {
|
||||||
head: Link<T>,
|
head: Link<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
type Link<T> = Option<Box<Node<T>>>;
|
||||||
enum Link<T> {
|
|
||||||
Empty,
|
|
||||||
More(Box<Node<T>>),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Node<T> {
|
struct Node<T> {
|
||||||
|
|
@ -27,21 +23,21 @@ struct Node<T> {
|
||||||
|
|
||||||
impl <T> List<T> {
|
impl <T> List<T> {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self { head: Link::Empty }
|
Self { head: None }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn push(&mut self, elem: T) {
|
pub fn push(&mut self, elem: T) {
|
||||||
let new_node = Node {
|
let new_node = Node {
|
||||||
elem: elem,
|
elem: elem,
|
||||||
next: std::mem::replace(&mut self.head, Link::Empty),
|
next: std::mem::replace(&mut self.head, None),
|
||||||
};
|
};
|
||||||
self.head = Link::More(Box::new(new_node));
|
self.head = Some(Box::new(new_node));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pop(&mut self) -> Option<T> {
|
pub fn pop(&mut self) -> Option<T> {
|
||||||
match std::mem::replace(&mut self.head, Link::Empty) {
|
match std::mem::replace(&mut self.head, None) {
|
||||||
Link::Empty => None,
|
None => None,
|
||||||
Link::More(node) => {
|
Some(node) => {
|
||||||
self.head = node.next;
|
self.head = node.next;
|
||||||
Some(node.elem)
|
Some(node.elem)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue