-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathmain.rs
More file actions
79 lines (67 loc) · 1.56 KB
/
main.rs
File metadata and controls
79 lines (67 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
type Link<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
struct Node<T> {
value: T,
next: Link<T>,
}
impl<T> Node<T> {
fn get(&self) -> &T {
&self.value
}
}
#[derive(Debug)]
pub struct LinkedList<T> {
head: Link<T>,
}
impl<T> LinkedList<T> {
fn new() -> Self {
LinkedList { head: None }
}
fn push(&mut self, item: T) {
let new_node = Box::new(Node {
value: item,
next: None,
});
let mut current = &mut self.head;
while let Some(ref mut node) = *current {
current = &mut node.next;
}
*current = Some(new_node);
}
fn pop(&mut self) -> Option<T> {
self.head.take().map(|node| {
self.head = node.next;
node.value
})
}
// TODO: optional
// fn greatest(&self) -> Option<&T>
// where
// T: Ord,
// {
// let mut current = &self.head;
// let mut greatest: Option<&T> = None;
//
// while let Some(ref node) = *current {
// let curr_val = node.get();
// if greatest.is_none() || curr_val > greatest.unwrap() {
// greatest = Some(curr_val);
// }
// current = &node.next;
// }
// greatest
// }
}
fn main() {
let mut list = LinkedList::new();
list.push(1);
list.push(2);
list.push(4);
list.push(5);
list.push(3);
list.pop();
if let Some(node) = &list.head {
assert_eq!(node.get(), &2);
}
// assert_eq!(list.greatest(), Some(&5));
}