-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathl6-list-safe.rs
More file actions
80 lines (69 loc) · 1.88 KB
/
Copy pathl6-list-safe.rs
File metadata and controls
80 lines (69 loc) · 1.88 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
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
val: u64,
prev: Option<Weak<RefCell<Node>>>,
next: Option<Rc<RefCell<Node>>>,
}
struct List {
head: Option<Rc<RefCell<Node>>>,
tail: Option<Rc<RefCell<Node>>>,
}
impl List {
fn new() -> Self {
Self { head: None, tail: None }
}
pub fn append(&mut self, val: u64) {
let new_node = Rc::new(RefCell::new(Node {
val,
prev: self.tail.as_ref().map(|tail| Rc::downgrade(tail)),
next: None,
}));
match self.tail.take() {
Some(old_tail) => {
old_tail.borrow_mut().next = Some(Rc::clone(&new_node));
self.tail = Some(new_node);
}
None => {
self.head = Some(Rc::clone(&new_node));
self.tail = Some(new_node);
}
}
}
pub fn prepend(&mut self, val: u64) {
let new_node = Rc::new(RefCell::new(Node {
val,
prev: None,
next: self.head.clone(),
}));
match self.head.take() {
Some(old_head) => {
old_head.borrow_mut().prev = Some(Rc::downgrade(&new_node));
self.head = Some(Rc::clone(&new_node));
}
None => {
self.head = Some(Rc::clone(&new_node));
self.tail = Some(new_node);
}
}
}
pub fn print(&self) {
let mut current = self.head.clone();
while let Some(node) = current {
print!("{} ", node.borrow().val);
current = node.borrow().next.clone();
}
println!();
}
}
fn main() {
let mut list = List::new();
list.append(1);
list.append(2);
list.append(3);
println!("After append:");
list.print();
list.prepend(0);
println!("After prepend:");
list.print();
}