forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
109 lines (100 loc) · 2.58 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
102
103
104
105
106
107
108
109
struct Node {
val: i32,
next: Option<Box<Node>>,
}
#[derive(Default)]
struct MyLinkedList {
head: Option<Box<Node>>,
}
/**
* `&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, index: i32) -> i32 {
let mut cur = match self.head {
None => return -1,
Some(ref n) => n,
};
let mut idx_cur = 0;
while idx_cur < index {
match cur.next {
None => return -1,
Some(ref next) => {
cur = next;
idx_cur += 1;
}
}
}
cur.val
}
fn add_at_head(&mut self, val: i32) {
self.head = Some(Box::new(Node {
val,
next: self.head.take(),
}));
}
fn add_at_tail(&mut self, val: i32) {
let new_node = Some(Box::new(Node { val, next: None }));
let mut cur = match self.head {
Some(ref mut n) => n,
None => {
self.head = new_node;
return;
}
};
while let Some(ref mut next) = cur.next {
cur = next;
}
cur.next = new_node;
}
fn add_at_index(&mut self, index: i32, val: i32) {
let mut dummy = Box::new(Node {
val: 0,
next: self.head.take()
});
let mut idx = 0;
let mut cur = &mut dummy;
while idx < index {
if let Some(ref mut next) = cur.next {
cur = next;
} else {
return
}
idx += 1;
}
cur.next = Some(Box::new(Node {
val,
next: cur.next.take()
}));
self.head = dummy.next;
}
fn delete_at_index(&mut self, index: i32) {
let mut dummy = Box::new(Node {
val: 0,
next: self.head.take(),
});
let mut idx = 0;
let mut cur = &mut dummy;
while idx < index {
if let Some(ref mut next) = cur.next {
cur = next;
}
idx += 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);
*/