Rust 编程,用 vector 实现栈

视频地址

头条地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
网易云课堂地址:https://study.163.com/course/introduction....

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());
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 1

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商