Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 29 additions & 8 deletions exercises/algorithm/algorithm1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
single linked list merge
This problem requires you to merge two ordered singly linked lists into one ordered singly linked list
*/
// I AM NOT DONE


use std::fmt::{self, Display, Formatter};
use std::ptr::NonNull;
Expand Down Expand Up @@ -35,7 +35,7 @@ impl<T> Default for LinkedList<T> {
}
}

impl<T> LinkedList<T> {
impl<T> LinkedList<T>{
pub fn new() -> Self {
Self {
length: 0,
Expand Down Expand Up @@ -69,14 +69,35 @@ impl<T> LinkedList<T> {
},
}
}
pub fn merge(list_a:LinkedList<T>,list_b:LinkedList<T>) -> Self
pub fn merge(mut list_a:LinkedList<T>,mut list_b:LinkedList<T>) -> Self
where
T: Ord + Clone,
{
//TODO
Self {
length: 0,
start: None,
end: None,
let mut list = LinkedList::<T>::new();
let mut idx_list_a:i32 = 0;
let mut idx_list_b:i32 = 0;
while idx_list_a<list_a.length.try_into().unwrap()||idx_list_b<list_b.length.try_into().unwrap() {
let mut node_val = list_a.get(idx_list_a);
if node_val.is_none() {
node_val = list_b.get(idx_list_b);
idx_list_b+=1;

}else if let Some(val_b) = list_b.get(idx_list_b){
let val_a= node_val.unwrap();
if val_a>val_b{
node_val = Some(val_b);
idx_list_b+=1;
}else{
idx_list_a+=1;
}
}else{
idx_list_a+=1;
};
let val= node_val.unwrap();
list.add((*val).clone());
}
list
}
}

Expand All @@ -94,7 +115,7 @@ where

impl<T> Display for Node<T>
where
T: Display,
T: Display ,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.next {
Expand Down
31 changes: 27 additions & 4 deletions exercises/algorithm/algorithm10.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
graph
This problem requires you to implement a basic graph functio
*/
// I AM NOT DONE

use std::collections::{HashMap, HashSet};
use std::fmt;
Expand All @@ -29,16 +28,40 @@ impl Graph for UndirectedGraph {
&self.adjacency_table
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
let (from, to, weight) = edge;
// 确保两个节点都存在于图中
self.add_node(from);
self.add_node(to);

let from_str = from.to_string();
let to_str = to.to_string();

// 无向图需要添加双向边
self.adjacency_table_mutable()
.get_mut(&from_str)
.unwrap()
.push((to_str.clone(), weight));

self.adjacency_table_mutable()
.get_mut(&to_str)
.unwrap()
.push((from_str, weight));
}
}
pub trait Graph {
fn new() -> Self;
fn adjacency_table_mutable(&mut self) -> &mut HashMap<String, Vec<(String, i32)>>;
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>>;
fn add_node(&mut self, node: &str) -> bool {
//TODO
true
let node_str = node.to_string();
// 如果节点已存在,返回false
if self.adjacency_table().contains_key(&node_str) {
false
} else {
// 新增节点,邻接列表初始为空
self.adjacency_table_mutable().insert(node_str, Vec::new());
true
}
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
Expand Down
17 changes: 15 additions & 2 deletions exercises/algorithm/algorithm2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
double linked list reverse
This problem requires you to reverse a doubly linked list
*/
// I AM NOT DONE


use std::fmt::{self, Display, Formatter};
use std::ptr::NonNull;
Expand Down Expand Up @@ -73,7 +73,20 @@ impl<T> LinkedList<T> {
}
}
pub fn reverse(&mut self){
// TODO
//// 当地反转双向链表
// 交换头指针和尾指针
std::mem::swap(&mut self.start, &mut self.end);

let mut current = self.start;
while let Some(mut curr_ptr) = current {
// 交换当前节点的prev和next指针
unsafe {
std::mem::swap(&mut (*curr_ptr.as_ptr()).prev, &mut (*curr_ptr.as_ptr()).next);
// 移动到下一个节点(原prev指针)
current = (*curr_ptr.as_ptr()).next;
}
}

}
}

Expand Down
17 changes: 15 additions & 2 deletions exercises/algorithm/algorithm3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,23 @@
This problem requires you to implement a sorting algorithm
you can use bubble sorting, insertion sorting, heap sorting, etc.
*/
// I AM NOT DONE

fn sort<T>(array: &mut [T]){
use std::ops::Deref;
use std::fmt::Display;

fn sort<T>(array: &mut [T])
where T: Ord +Display+ std::fmt::Debug {
//TODO
let size = array.len();
println!("{size}");
for i in 1..size{
let mut j = i;
while j>0&&array[j-1]>array[j] {
array.swap(j, j-1);
j-=1;
}
}

}
#[cfg(test)]
mod tests {
Expand Down
41 changes: 37 additions & 4 deletions exercises/algorithm/algorithm4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This problem requires you to implement a basic interface for a binary tree
*/

//I AM NOT DONE

use std::cmp::Ordering;
use std::fmt::Debug;

Expand Down Expand Up @@ -50,23 +50,56 @@ where

// Insert a value into the BST
fn insert(&mut self, value: T) {
//TODO
if let Some(ref mut root_node) = self.root {
root_node.insert(value);
} else {
// 根节点为空时直接创建新节点
self.root = Some(Box::new(TreeNode::new(value)));
}
}

// Search for a value in the BST
fn search(&self, value: T) -> bool {
//TODO
true
self.root.as_ref().map_or(false, |node| node.search(&value))
}
}

impl<T> TreeNode<T>
where
T: Ord,
T: Ord+PartialEq,
{
// Insert a node into the tree
fn insert(&mut self, value: T) {
//TODO
match self.value.cmp(&value) {
Ordering::Greater => {
// 插入到左子树
if let Some(ref mut left_child) = self.left {
left_child.insert(value);
} else {
self.left = Some(Box::new(TreeNode::new(value)));
}
}
Ordering::Less => {
// 插入到右子树
if let Some(ref mut right_child) = self.right {
right_child.insert(value);
} else {
self.right = Some(Box::new(TreeNode::new(value)));
}
}
Ordering::Equal => {
// 相等的值不插入(BST通常不存储重复值)
}
}
}
fn search(&self, value: &T) -> bool {
match self.value.cmp(value) {
Ordering::Equal => true,
Ordering::Greater => self.left.as_ref().map_or(false, |node| node.search(value)),
Ordering::Less => self.right.as_ref().map_or(false, |node| node.search(value)),
}
}
}

Expand Down
18 changes: 16 additions & 2 deletions exercises/algorithm/algorithm5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This problem requires you to implement a basic BFS algorithm
*/

//I AM NOT DONE

use std::collections::VecDeque;

// Define a graph
Expand All @@ -29,8 +29,22 @@ impl Graph {
fn bfs_with_return(&self, start: usize) -> Vec<usize> {

//TODO

let n = self.adj.len();
let mut i = 0;
let mut visit_order = vec![];
let mut visited = vec![0;n];
visit_order.push(start);
visited[start] = 1;
while i<visit_order.len(){
let idx = visit_order[i];
for j in self.adj[idx].iter() {
if visited[*j] == 0{
visit_order.push(j.clone());
visited[*j] = 1;
}
}
i+=1;
}
visit_order
}
}
Expand Down
10 changes: 9 additions & 1 deletion exercises/algorithm/algorithm6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This problem requires you to implement a basic DFS traversal
*/

// I AM NOT DONE

use std::collections::HashSet;

struct Graph {
Expand All @@ -24,6 +24,14 @@ impl Graph {

fn dfs_util(&self, v: usize, visited: &mut HashSet<usize>, visit_order: &mut Vec<usize>) {
//TODO
if visited.contains(&v) {
return ();
}
visited.insert(v.clone());
visit_order.push(v.clone());
for idx in self.adj[v].iter(){
self.dfs_util(*idx,visited,visit_order);
}
}

// Perform a depth-first search on the graph, return the order of visited nodes
Expand Down
43 changes: 38 additions & 5 deletions exercises/algorithm/algorithm7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
This question requires you to use a stack to achieve a bracket match
*/

// I AM NOT DONE
#[derive(Debug)]
struct Stack<T> {
size: usize,
Expand Down Expand Up @@ -32,7 +31,11 @@ impl<T> Stack<T> {
}
fn pop(&mut self) -> Option<T> {
// TODO
None
if self.size ==0{
return None;
}
self.size -= 1;
Some(self.data.pop()?)
}
fn peek(&self) -> Option<&T> {
if 0 == self.size {
Expand Down Expand Up @@ -73,7 +76,8 @@ impl<T: Clone> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if !self.0.is_empty() {
self.0.size -= 1;self.0.data.pop()
self.0.size -= 1;
self.0.data.pop()
}
else {
None
Expand Down Expand Up @@ -101,8 +105,37 @@ impl<'a, T> Iterator for IterMut<'a, T> {

fn bracket_match(bracket: &str) -> bool
{
//TODO
true
//TODO

let mut stack = Stack::new();

for c in bracket.chars() {
match c {
// 遇到左括号则入栈
'(' | '{' | '[' => stack.push(c),
// 遇到右括号则检查匹配
')' => {
if stack.pop() != Some('(') {
return false;
}
}
'}' => {
if stack.pop() != Some('{') {
return false;
}
}
']' => {
if stack.pop() != Some('[') {
return false;
}
}
// 忽略其他字符
_ => (),
}
}

// 所有括号处理完毕后,栈必须为空才是完全匹配
stack.is_empty()
}

#[cfg(test)]
Expand Down
Loading