-
Notifications
You must be signed in to change notification settings - Fork 267
/
singly_linked_list.rs
51 lines (45 loc) · 1 KB
/
singly_linked_list.rs
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
#[derive(Debug)]
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
#[derive(Debug)]
struct LinkedList<T> {
head: Option<Box<Node<T>>>,
size: usize,
}
impl<T> LinkedList<T> {
pub fn new() -> Self {
LinkedList {
head: None,
size: 0,
}
}
pub fn len(&self) -> usize {
self.size
}
pub fn push(&mut self, data: T) {
self.head = Some(Box::new(Node {
data: data,
next: self.head.take(),
}));
self.size += 1;
}
pub fn pop(&mut self) -> Option<T> {
self.head.take().map(|h| {
self.head = h.next;
self.size -= 1;
h.data
})
}
}
fn main() {
let mut linked_list: LinkedList<u16> = LinkedList::new();
linked_list.push(1);
linked_list.push(2);
linked_list.push(3);
println!("{:#?}", linked_list);
linked_list.pop();
println!("{:#?}", linked_list);
println!("Linked List Length: {}", linked_list.len());
}