Skip to content

Commit

Permalink
finished hw2
Browse files Browse the repository at this point in the history
  • Loading branch information
rezo8 committed Dec 24, 2020
1 parent 77bdce6 commit 03f5112
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 1 deletion.
13 changes: 13 additions & 0 deletions hw02/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "hw02"
version = "0.1.0"
authors = ["RibhiEl-Zaru <[email protected]>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clippy = { version = "*", optional = true }

[features]
default = []
112 changes: 112 additions & 0 deletions hw02/src/first.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use std::mem;

#[derive(Debug)]
pub struct BST {
head: Link
}

#[derive(Debug)]
enum Link {
Empty,
More(Box<Node>),
}

#[derive(Debug)]
struct Node {
elem: i32,
left: Link,
right: Link,
}


impl BST {
pub fn new() -> Self {
BST { head: Link::Empty }
}

/*
Insert an element into the BST. Return
true if successful, or false if the element was already in the BST.
*/
pub fn insert(&mut self, num: i32) -> bool {
return self.head.insert(num);
}

/*
Search for an element in the BST. Return
true iff the element was found.
*/
pub fn search(&self, num: i32) -> bool{
return self.head.search(num);
}
}


impl Link {
pub fn insert(&mut self, num: i32)-> bool {
match self {
Link::Empty => {
*self = Link::More(Box::new(Node{ elem : num, left : Link::Empty, right : Link::Empty}));
return true;
}
Link::More(node) => {
if num == node.elem {
return false;
}
else if num > node.elem {
return node.right.insert(num);
}
else {
return node.left.insert(num);
}
}
}
}

pub fn search(&self, num: i32) -> bool {
match self {
Link::Empty => {
return false;
}
Link::More(node) => {
if num == node.elem {
return true;
}
else if num > node.elem {
return node.right.search(num);
}
else {
return node.left.search(num);
}
}
}
}

}

#[cfg(test)]
mod test {
use super::BST;

#[test]
fn test_BST() {
// ...
let mut bst = BST::new();
assert!(bst.insert(15));
assert!(bst.insert(2));
assert!(bst.insert(20));

assert!(bst.search(2));
assert!(bst.search(20));
assert!(bst.search(15));
assert!(!bst.search(2220));


assert!(bst.insert(2220));
assert!(bst.search(2220));


println!("{:#?}", bst);

}
}
3 changes: 3 additions & 0 deletions hw02/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]

pub mod first;
3 changes: 3 additions & 0 deletions hw02/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() {
println!("Hello, world!");
}
1 change: 0 additions & 1 deletion hw02/starter
Submodule starter deleted from 22cac4
Empty file added return
Empty file.

0 comments on commit 03f5112

Please sign in to comment.