题解 | #链表中倒数最后k个结点# | Rust
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
/** * #[derive(PartialEq, Eq, Debug, Clone)] * pub struct ListNode { * pub val: i32, * pub next: Option<Box<ListNode>> * } * * impl ListNode { * #[inline] * fn new(val: i32) -> Self { * ListNode { * val: val, * next: None, * } * } * } */ struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead ListNode类 * @param k int整型 * @return ListNode类 */ pub fn FindKthToTail(&self, pHead: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> { if pHead.is_none() || k == 0{ return None; } let mut fast = &pHead; let mut k = k; while k > 1 { fast = &fast.as_ref().unwrap().next; if fast.is_none() { return None; } k-=1; } let mut slow = &pHead; while fast.as_ref().unwrap().next.is_none() == false { fast = &fast.as_ref().unwrap().next; slow = &slow.as_ref().unwrap().next; } return slow.clone(); } }