forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
101 lines (95 loc) · 2.53 KB
/
Solution.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
#[derive(Default)]
struct MyLinkedList {
head: Option<Box<ListNode>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MyLinkedList {
fn new() -> Self {
Default::default()
}
fn get(&self, mut index: i32) -> i32 {
if self.head.is_none() {
return -1;
}
let mut cur = self.head.as_ref().unwrap();
while index > 0 {
match cur.next {
None => {
return -1;
}
Some(ref next) => {
cur = next;
index -= 1;
}
}
}
cur.val
}
fn add_at_head(&mut self, val: i32) {
self.head = Some(
Box::new(ListNode {
val,
next: self.head.take(),
})
);
}
fn add_at_tail(&mut self, val: i32) {
let new_node = Some(Box::new(ListNode { val, next: None }));
if self.head.is_none() {
self.head = new_node;
return;
}
let mut cur = self.head.as_mut().unwrap();
while let Some(ref mut next) = cur.next {
cur = next;
}
cur.next = new_node;
}
fn add_at_index(&mut self, mut index: i32, val: i32) {
let mut dummy = Box::new(ListNode {
val: 0,
next: self.head.take(),
});
let mut cur = &mut dummy;
while index > 0 {
if cur.next.is_none() {
return;
}
cur = cur.next.as_mut().unwrap();
index -= 1;
}
cur.next = Some(
Box::new(ListNode {
val,
next: cur.next.take(),
})
);
self.head = dummy.next;
}
fn delete_at_index(&mut self, mut index: i32) {
let mut dummy = Box::new(ListNode {
val: 0,
next: self.head.take(),
});
let mut cur = &mut dummy;
while index > 0 {
if let Some(ref mut next) = cur.next {
cur = next;
}
index -= 1;
}
cur.next = cur.next.take().and_then(|n| n.next);
self.head = dummy.next;
}
}/**
* Your MyLinkedList object will be instantiated and called as such:
* let obj = MyLinkedList::new();
* let ret_1: i32 = obj.get(index);
* obj.add_at_head(val);
* obj.add_at_tail(val);
* obj.add_at_index(index, val);
* obj.delete_at_index(index);
*/