2023-02-09 00:25:01 +08:00
|
|
|
/*
|
2023-02-05 16:25:42 +08:00
|
|
|
* File: stack.rs
|
|
|
|
* Created Time: 2023-02-05
|
2024-01-02 01:25:37 +08:00
|
|
|
* Author: codingonion (coderonion@gmail.com)
|
2023-02-09 00:25:01 +08:00
|
|
|
*/
|
|
|
|
|
2024-10-23 18:49:47 +08:00
|
|
|
use hello_algo_rust::include::print_util;
|
2023-02-05 16:25:42 +08:00
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
pub fn main() {
|
|
|
|
// 初始化栈
|
|
|
|
// 在 rust 中,推荐将 Vec 当作栈来使用
|
|
|
|
let mut stack: Vec<i32> = Vec::new();
|
|
|
|
|
|
|
|
// 元素入栈
|
|
|
|
stack.push(1);
|
|
|
|
stack.push(3);
|
|
|
|
stack.push(2);
|
|
|
|
stack.push(5);
|
|
|
|
stack.push(4);
|
|
|
|
print!("栈 stack = ");
|
2023-02-09 00:25:01 +08:00
|
|
|
print_util::print_array(&stack);
|
2023-02-05 16:25:42 +08:00
|
|
|
|
|
|
|
// 访问栈顶元素
|
2023-11-13 14:18:29 +08:00
|
|
|
let peek = stack.last().unwrap();
|
2023-02-05 16:25:42 +08:00
|
|
|
print!("\n栈顶元素 peek = {peek}");
|
|
|
|
|
|
|
|
// 元素出栈
|
|
|
|
let pop = stack.pop().unwrap();
|
|
|
|
print!("\n出栈元素 pop = {pop},出栈后 stack = ");
|
2023-02-09 00:25:01 +08:00
|
|
|
print_util::print_array(&stack);
|
2023-02-05 16:25:42 +08:00
|
|
|
|
|
|
|
// 获取栈的长度
|
|
|
|
let size = stack.len();
|
|
|
|
print!("\n栈的长度 size = {size}");
|
|
|
|
|
|
|
|
// 判断栈是否为空
|
|
|
|
let is_empty = stack.is_empty();
|
|
|
|
print!("\n栈是否为空 = {is_empty}");
|
2024-03-16 02:13:41 +08:00
|
|
|
}
|