数据结构

Rust 实现二进制转换

Rust 实现二进制转换

fn divide_by_two(mut dec_num: u32) -> String { // save rem with Stack let mut rem_stack = Stack::new(); while dec_num > 0 { let rem = dec_num % 2; rem_stack.push(rem); dec_num /=2; } // connect stack items to String let mut bin_str = "".to_string(); while !rem_stack.is_empty() { let rem = rem_stack.pop().unwrap().to_string(); bin_str += &rem; } bin_str } 那么二进制实现了,八进制,16进制也容易实现

Read More
使用 栈 实现括号匹配

使用 栈 实现括号匹配

使用 栈数据结构 实现括号匹配的功能 rust 实现 将所有符号依次存储到Vec 使用 balance 判断是否平衡 ‘(’ 入栈 否则 出栈 Stack.is_empty && balance 匹配成功 // par_check.rs fn par_checker(par:&str) -> bool { let mut char_list = Vec::new(); for c in char_list { char_list.push(c) } let mut index = 0; let mut balance = true; let mut stack = Stack::new(); while index < char_list.len() && balance { let c = char_list[index]; if '(' == c { stack.push(c); } else { if stack.is_empty() { balance = false; } else { let _r = stack.pop(); } } index += 1; } balance && stack.is_empty(); } 当前程序有弊端就是只能适配小括号,那如何处理三种括号呢?是有一个匹配函数

Read More
rust 实现线性数据结构

rust 实现线性数据结构

线性数据结构 数组、栈、队列、双端队列数据项的顺序由添加或者删除的顺序决定 栈 - LIFO 先进后出原则 根据栈的特性可以抽象以下数据操作: new() push(item) pop() peek() is_empty() size() RUST 实现栈 // stack.rs #[derive(Debug)] struct Stack<T> { top: usize, data: Vec<T> } impl <T> Stack <T> { fn new() -> Self { Stack { top: 0, data: Vec::new() } } fn push(&mut self, val: T) { self.data.push(val); self.top += 1; } fn pop(&mut self) -> Option<T> { if self.top == 0 {return None;} self.top -= 1; // 使用Vec数据结构的pop() self.data.pop(); } fn peek(&self) -> Option<T> { if self.top == 0 { return None; } self.data.get(self.top - 1); } fn is_empty(&self) -> usize { 0 == self.top } fn size(&self) -> usize { self.top } }

Read More