Rust 程式設計,用連結串列實現棧

linghuyichong發表於2020-04-12

影片地址

頭條地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
網易雲課堂地址:https://study.163.com/course/introduction....

github地址

github地址

原始碼實現

#[derive(Debug)]
struct Stack<T> {
    top: Option<Box<StackNode<T>>>,
}

#[derive(Clone, Debug)]
struct StackNode<T> {
    data: T,
    next: Option<Box<StackNode<T>>>,
}

impl <T> StackNode<T> {
    fn new(data: T) -> StackNode<T> {
        StackNode { data: data, next: None }
    }
}

impl<T> Stack<T> {
    fn new() -> Stack<T> {
        Stack{ top: None }
    }

    fn push(&mut self, data: T) {
        let mut node = StackNode::new(data);
        let next = self.top.take();
        node.next = next;
        self.top = Some(Box::new(node));
    }

    fn pop(&mut self) -> Option<T> {
        let val = self.top.take();
        match val {
            None => None,
            Some(mut x) => {
                self.top = x.next.take();
                Some(x.data)
            },
        }
    }
}

fn main() {
    let mut ss = Stack::new();
    ss.push(1);
    ss.push(1);
    ss.push(1);

    println!("{:#?}", ss);

    ss.pop();
    ss.pop();

    println!("{:#?}", ss);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章