@@ -114,4 +114,82 @@ impl MyLinkedList {
114
114
115
115
## 学习感想
116
116
117
- 也没啥好说的,rust只要写出来,基本是对的,没有用take的形式,而是全部去除了option用ref
117
+ 也没啥好说的,rust只要写出来,基本是对的,没有用take的形式,而是全部去除了option用ref
118
+
119
+
120
+ ``` rust
121
+ struct MyLinkedList {
122
+ head : Option <Box <ListNode >>,
123
+ cnt : i32 ,
124
+ }
125
+
126
+ struct ListNode {
127
+ val : i32 ,
128
+ next : Option <Box <ListNode >>,
129
+ }
130
+
131
+ /**
132
+ * `&self` means the method takes an immutable reference.
133
+ * If you need a mutable reference, change it to `&mut self` instead.
134
+ */
135
+ impl MyLinkedList {
136
+
137
+ fn new () -> Self {
138
+ Self {
139
+ head : None ,
140
+ cnt : 0i32 ,
141
+ }
142
+ }
143
+
144
+ fn get (& self , mut index : i32 ) -> i32 {
145
+ if index >= self . cnt { return - 1i32 }
146
+ let mut ptr : & Box <ListNode > = self . head. as_ref (). unwrap ();
147
+ while index > 0i32 {
148
+ ptr = ptr . next. as_ref (). unwrap ();
149
+ index -= 1i32 ;
150
+ }
151
+ ptr . val
152
+ }
153
+
154
+ fn add_at_head (& mut self , val : i32 ) {
155
+ self . add_at_index (0i32 , val );
156
+ }
157
+
158
+ fn add_at_tail (& mut self , val : i32 ) {
159
+ self . add_at_index (self . cnt, val );
160
+ }
161
+
162
+ fn add_at_index (& mut self , mut index : i32 , val : i32 ) {
163
+ if index > self . cnt { return }
164
+ let mut ptr : & mut Option <Box <ListNode >> = & mut self . head;
165
+ while index > 0i32 {
166
+ ptr = & mut ptr . as_mut (). unwrap (). next;
167
+ index -= 1i32 ;
168
+ }
169
+ self . cnt += 1i32 ;
170
+ * ptr = Some (Box :: new (ListNode { val : val , next : ptr . take () }))
171
+ }
172
+
173
+ fn delete_at_index (& mut self , mut index : i32 ) {
174
+ if index >= self . cnt { return }
175
+ let mut ptr : & mut Option <Box <ListNode >> = & mut self . head;
176
+ while index > 0i32 {
177
+ ptr = & mut ptr . as_mut (). unwrap (). next;
178
+ index -= 1i32 ;
179
+ }
180
+ let nxt : Option <Box <ListNode >> = ptr . take (). unwrap (). next. take ();
181
+ * ptr = nxt ;
182
+ self . cnt -= 1i32 ;
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Your MyLinkedList object will be instantiated and called as such:
188
+ * let obj = MyLinkedList::new();
189
+ * let ret_1: i32 = obj.get(index);
190
+ * obj.add_at_head(val);
191
+ * obj.add_at_tail(val);
192
+ * obj.add_at_index(index, val);
193
+ * obj.delete_at_index(index);
194
+ */
195
+ ```
0 commit comments