美文网首页RUST编程
Rust编程知识拾遗:Rust 编程,用链表实现栈

Rust编程知识拾遗:Rust 编程,用链表实现栈

作者: 令狐壹冲 | 来源:发表于2020-04-18 11:01 被阅读0次

视频地址

头条地址:https://www.ixigua.com/i6765442674582356483
B站地址:https://www.bilibili.com/video/av78062009?p=1
网易云课堂地址:https://study.163.com/course/introduction.htm?courseId=1209596906#/courseDetail?tab=1

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);
}

相关文章

网友评论

    本文标题:Rust编程知识拾遗:Rust 编程,用链表实现栈

    本文链接:https://www.haomeiwen.com/subject/cdfvvhtx.html