Skip to content

Commit d1173be

Browse files
committedFeb 11, 2022
feat: add rust solution to lcof problem: No.22
面试题22. 链表中倒数第k个节点
1 parent bec431b commit d1173be

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
 

‎lcof/面试题22. 链表中倒数第k个节点/README.md

+35
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,41 @@ public:
137137
};
138138
```
139139
140+
### **Rust**
141+
142+
```rust
143+
// Definition for singly-linked list.
144+
// #[derive(PartialEq, Eq, Clone, Debug)]
145+
// pub struct ListNode {
146+
// pub val: i32,
147+
// pub next: Option<Box<ListNode>>
148+
// }
149+
//
150+
// impl ListNode {
151+
// #[inline]
152+
// fn new(val: i32) -> Self {
153+
// ListNode {
154+
// next: None,
155+
// val
156+
// }
157+
// }
158+
// }
159+
impl Solution {
160+
pub fn get_kth_from_end(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
161+
let mut fast = &head;
162+
for _ in 0..k {
163+
fast = &fast.as_ref().unwrap().next;
164+
}
165+
let mut slow = &head;
166+
while let (Some(nf), Some(ns)) = (fast, slow) {
167+
fast = &nf.next;
168+
slow = &ns.next;
169+
}
170+
slow.to_owned()
171+
}
172+
}
173+
```
174+
140175
### **...**
141176

142177
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Definition for singly-linked list.
2+
// #[derive(PartialEq, Eq, Clone, Debug)]
3+
// pub struct ListNode {
4+
// pub val: i32,
5+
// pub next: Option<Box<ListNode>>
6+
// }
7+
//
8+
// impl ListNode {
9+
// #[inline]
10+
// fn new(val: i32) -> Self {
11+
// ListNode {
12+
// next: None,
13+
// val
14+
// }
15+
// }
16+
// }
17+
impl Solution {
18+
pub fn get_kth_from_end(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
19+
let mut fast = &head;
20+
for _ in 0..k {
21+
fast = &fast.as_ref().unwrap().next;
22+
}
23+
let mut slow = &head;
24+
while let (Some(nf), Some(ns)) = (fast, slow) {
25+
fast = &nf.next;
26+
slow = &ns.next;
27+
}
28+
slow.to_owned()
29+
}
30+
}

0 commit comments

Comments
 (0)
Please sign in to comment.