-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleet_singly_ll.rs
112 lines (97 loc) · 2.58 KB
/
leet_singly_ll.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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
pub type LinkedType = Option<Box<Node>>;
#[derive(Debug)]
pub struct Node {
pub val: i32,
pub next: Option<Box<Node>>,
}
#[derive(Default, Debug)]
pub struct MyLinkedList {
pub head: Option<Box<Node>>,
}
// trait Foo: CloneFoo {};
// trait CloneFoo {
// fn clone_foo(&self) -> Box<dyn Foo>;
// }
// imp CloneFoo for MyLinkedList {
// }
impl MyLinkedList {
pub fn new() -> Self {
Default::default()
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1 */
/// O(n)
pub fn get(&self, index: i32) -> i32 {
let mut curr = match self.head {
Some(ref a) => a,
None => return -1,
};
let mut idx_curr = 0;
while idx_curr < index {
if let Some(ref next) = curr.next {
curr = next;
idx_curr += 1;
} else {
return -1;
};
}
curr.val
}
/// O(1)
pub fn add_at_head(&mut self, val: i32) {
self.head = Some(Box::new(Node {
val,
next: self.head.take(),
}))
}
/// O(n)
pub fn add_at_tail(&mut self, val: i32) {
let mut curr = match self.head {
Some(ref mut a) => a,
None => {
self.head = Some(Box::new(Node { val, next: None }));
return;
}
};
while let Some(ref mut next) = curr.next {
curr = next;
}
curr.next = Some(Box::new(Node { val, next: None }));
}
/// O(n)
pub fn add_at_index(&mut self, index: i32, val: i32) {
let mut dummy_head = Box::new(Node {
val: 0,
next: self.head.take(),
});
let mut idx = 0;
let mut curr = &mut dummy_head;
while idx < index {
if let Some(ref mut next) = curr.next {
curr = next;
}
idx += 1;
}
curr.next = Some(Box::new(Node {
val,
next: curr.next.take(),
}));
self.head = dummy_head.next;
}
/// O(n)
pub fn delete_at_index(&mut self, index: i32) {
let mut dummy_head = Box::new(Node {
val: 0,
next: self.head.take(),
});
let mut idx = 0;
let mut curr = &mut dummy_head;
while idx < index {
if let Some(ref mut next) = curr.next {
curr = next;
}
idx += 1;
}
curr.next = curr.next.take().and_then(|a| a.next);
self.head = dummy_head.next;
}
}