Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
baiyazi233 committed Apr 16, 2024
1 parent 5926fd3 commit 9e03e1e
Show file tree
Hide file tree
Showing 10 changed files with 251 additions and 35 deletions.
61 changes: 48 additions & 13 deletions exercises/algorithm/algorithm1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@
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;
use std::vec::*;

#[derive(Debug)]
struct Node<T> {
struct Node<T>
where
T: Ord + Clone + Display,
{
val: T,
next: Option<NonNull<Node<T>>>,
}

impl<T> Node<T> {
impl<T> Node<T>
where
T: Ord + Clone + Display,
{
fn new(t: T) -> Node<T> {
Node {
val: t,
Expand All @@ -23,19 +29,28 @@ impl<T> Node<T> {
}
}
#[derive(Debug)]
struct LinkedList<T> {
struct LinkedList<T>
where
T: Ord + Clone + Display,
{
length: u32,
start: Option<NonNull<Node<T>>>,
end: Option<NonNull<Node<T>>>,
}

impl<T> Default for LinkedList<T> {
impl<T> Default for LinkedList<T>
where
T: Ord + Clone + Display,
{
fn default() -> Self {
Self::new()
}
}

impl<T> LinkedList<T> {
impl<T> LinkedList<T>
where
T: Ord + Clone + Display,
{
pub fn new() -> Self {
Self {
length: 0,
Expand Down Expand Up @@ -72,17 +87,37 @@ impl<T> LinkedList<T> {
pub fn merge(list_a:LinkedList<T>,list_b:LinkedList<T>) -> Self
{
//TODO
Self {
length: 0,
start: None,
end: None,
let mut result = LinkedList::new();
let mut current_a = list_a.start;
let mut current_b = list_b.start;

while let (Some(node_a), Some(node_b)) = (current_a, current_b) {
unsafe {
if (*node_a.as_ptr()).val <= (*node_b.as_ptr()).val {
result.add((*node_a.as_ptr()).val.clone());
current_a = (*node_a.as_ptr()).next;
} else {
result.add((*node_b.as_ptr()).val.clone());
current_b = (*node_b.as_ptr()).next;
}
}
}
}

let mut remaining = if current_a.is_some() { current_a } else { current_b };
while let Some(node) = remaining {
unsafe {
result.add((*node.as_ptr()).val.clone());
remaining = (*node.as_ptr()).next;
}
}

result
}
}

impl<T> Display for LinkedList<T>
where
T: Display,
T: Ord + Clone + Display,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.start {
Expand All @@ -94,7 +129,7 @@ where

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


use std::collections::{HashMap, HashSet};
use std::fmt;
Expand Down Expand Up @@ -30,6 +30,17 @@ impl Graph for UndirectedGraph {
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
let (node1, node2, weight) = edge;

// 给node1添加到node2的边
self.adjacency_table.entry(node1.to_string())
.or_insert_with(Vec::new)
.push((node2.to_string(), weight));

// 由于是无向图,还需要给node2添加到node1的边
self.adjacency_table.entry(node2.to_string())
.or_insert_with(Vec::new)
.push((node1.to_string(), weight));
}
}
pub trait Graph {
Expand All @@ -38,10 +49,26 @@ pub trait Graph {
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>>;
fn add_node(&mut self, node: &str) -> bool {
//TODO
true
if self.adjacency_table_mutable().contains_key(node) {
false
} else {
self.adjacency_table_mutable().insert(node.to_string(), Vec::new());
true
}
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
let (node1, node2, weight) = edge;

// 给node1添加到node2的边
self.adjacency_table_mutable().entry(node1.to_string())
.or_insert_with(Vec::new)
.push((node2.to_string(), weight));

// 由于是无向图,还需要给node2添加到node1的边
self.adjacency_table_mutable().entry(node2.to_string())
.or_insert_with(Vec::new)
.push((node1.to_string(), weight));
}
fn contains(&self, node: &str) -> bool {
self.adjacency_table().get(node).is_some()
Expand Down
14 changes: 13 additions & 1 deletion 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 @@ -74,6 +74,18 @@ impl<T> LinkedList<T> {
}
pub fn reverse(&mut self){
// TODO
let mut current = self.start;
while let Some(mut current_node) = current {
// 交换当前节点的 next 和 prev
unsafe {
let mut node = current_node.as_mut();
std::mem::swap(&mut node.prev, &mut node.next);
}
// 移动到原来的 prev 节点,现在是 next
current = unsafe { current_node.as_ref().prev };
}
// 交换链表的 start 和 end
std::mem::swap(&mut self.start, &mut self.end);
}
}

Expand Down
11 changes: 9 additions & 2 deletions exercises/algorithm/algorithm3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@
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]){

fn sort<T: std::cmp::PartialOrd>(array: &mut [T]){
//TODO
for i in 0..array.len() {
for j in 0..array.len() - i - 1 {
if array[j] > array[j + 1] {
array.swap(j, j + 1);
}
}
}
}
#[cfg(test)]
mod tests {
Expand Down
35 changes: 33 additions & 2 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 @@ -51,12 +51,19 @@ where
// Insert a value into the BST
fn insert(&mut self, value: T) {
//TODO
match self.root {
Some(ref mut node) => node.insert(value),
None => self.root = Some(Box::new(TreeNode::new(value))),
}
}

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

Expand All @@ -67,6 +74,30 @@ where
// Insert a node into the tree
fn insert(&mut self, value: T) {
//TODO
match value.cmp(&self.value) {
Ordering::Less => {
if let Some(ref mut left) = self.left {
left.insert(value);
} else {
self.left = Some(Box::new(TreeNode::new(value)));
}
},
Ordering::Greater => {
if let Some(ref mut right) = self.right {
right.insert(value);
} else {
self.right = Some(Box::new(TreeNode::new(value)));
}
},
Ordering::Equal => {} // 如果值相等,我们不做任何操作,也可以在这里处理重复值
}
}
fn search(&self, value: &T) -> bool {
match value.cmp(&self.value) {
Ordering::Equal => true,
Ordering::Less => self.left.as_ref().map_or(false, |node| node.search(value)),
Ordering::Greater => self.right.as_ref().map_or(false, |node| node.search(value)),
}
}
}

Expand Down
22 changes: 18 additions & 4 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 @@ -27,10 +27,24 @@ impl Graph {

// Perform a breadth-first search on the graph, return the order of visited nodes
fn bfs_with_return(&self, start: usize) -> Vec<usize> {

//TODO

let mut visit_order = vec![];
let mut visited = vec![false; self.adj.len()]; // Track visited nodes
let mut queue = VecDeque::new();

// Start BFS from the given start node
visited[start] = true;
queue.push_back(start);

while let Some(node) = queue.pop_front() {
visit_order.push(node);
for &neighbor in &self.adj[node] {
if !visited[neighbor] {
visited[neighbor] = true;
queue.push_back(neighbor);
}
}
}

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
visited.insert(v); // 标记当前节点为已访问
visit_order.push(v); // 将当前节点加入访问顺序列表

for &i in &self.adj[v] {
if !visited.contains(&i) { // 对于每一个未访问的邻接节点
self.dfs_util(i, visited, visit_order); // 递归访问
}
}
}

// Perform a depth-first search on the graph, return the order of visited nodes
Expand Down
22 changes: 19 additions & 3 deletions exercises/algorithm/algorithm7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
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 +32,12 @@ impl<T> Stack<T> {
}
fn pop(&mut self) -> Option<T> {
// TODO
None
if self.size > 0 {
self.size -= 1;
self.data.pop()
} else {
None
}
}
fn peek(&self) -> Option<&T> {
if 0 == self.size {
Expand Down Expand Up @@ -102,7 +107,18 @@ impl<'a, T> Iterator for IterMut<'a, T> {
fn bracket_match(bracket: &str) -> bool
{
//TODO
true
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

0 comments on commit 9e03e1e

Please sign in to comment.