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

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

作者: 令狐壹冲 | 来源:发表于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地址

    栈介绍

    栈和队列一样,只能从固定的方向进出,不过和队列不同的是,队列是先进先出,而栈则是后进先出。也就是说,栈只能从一端进行添加和删除。

    栈操作

    • 初始化;
    • 入栈;
    • 出栈;
    • 获取栈顶位置。

    源码实现

    本实现借助vector进行实现,在实现时,限定栈的大小。

    #[derive(Debug)]
    struct Stack<T> {
        data: Vec<T>,
        top: usize,
    }
    
    impl <T> Stack<T> {
        fn new(size: usize) -> Self {
            Stack { 
                data: Vec::with_capacity(size),
                top: 0,
             }
        }
    
        fn push(&mut self, item: T) -> Result<(), String> {
            if self.top >= self.data.capacity() {
                return Err(String::from("There is no space in stack!"))
            }
    
            self.data.push(item);
            self.top += 1;
            Ok(())
        }
    
        fn pop(&mut self) -> Option<T> {
            if self.top == 0 {
                return None
            }
    
            self.top -= 1;
            self.data.pop()
        }
    
        fn top(&self) -> usize {
            self.top
        }
    
    }
    
    fn main() {
        let mut s = Stack::new(4);
        if let Err(error) = s.push(1) {
            println!("err: {}", error);
        } 
    
        if let Err(error) = s.push(2) {
            println!("err: {}", error);
        } 
    
        println!("stack :  {:?}", s);
        
        for _ in 0..3 {
            if let Some(a) = s.pop() {
                println!("a = {}", a);
            } else {
                println!("stack empty");
            }
        }
    
        println!("top is {}", s.top());
    }
    
    

    相关文章

      网友评论

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

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