876.链表的中间结点
This commit is contained in:
parent
c4dba758da
commit
4e23218ada
|
@ -83,6 +83,7 @@ mod q0746;
|
|||
mod q0781;
|
||||
mod q0783;
|
||||
mod q0872;
|
||||
mod q0876;
|
||||
mod q0897;
|
||||
mod q0912;
|
||||
mod q0918;
|
||||
|
|
|
@ -0,0 +1,58 @@
|
|||
use crate::Solution;
|
||||
use crate::structure::ListNode;
|
||||
|
||||
|
||||
impl Solution {
|
||||
/// [876.链表的中间结点](https://leetcode-cn.com/problems/middle-of-the-linked-list/)
|
||||
///
|
||||
/// 2021-11-11 10:16:51
|
||||
///
|
||||
/// 给定一个头结点为 `head` 的非空单链表,返回链表的中间结点。
|
||||
///
|
||||
/// 如果有两个中间结点,则返回第二个中间结点。
|
||||
///
|
||||
/// * **示例 1:**
|
||||
/// + **输入:** \[1,2,3,4,5\]
|
||||
/// + **输出:** 此列表中的结点 3 \(序列化形式:\[3,4,5\]\)
|
||||
/// + 返回的结点值为 3 。 \(测评系统对该结点序列化表述是 \[3,4,5\]\)。
|
||||
/// + 注意,我们返回了一个 ListNode 类型的对象 ans,这样:
|
||||
/// + ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
|
||||
/// * **示例 2:**
|
||||
/// + **输入:** \[1,2,3,4,5,6\]
|
||||
/// + **输出:** 此列表中的结点 4 \(序列化形式:\[4,5,6\]\)
|
||||
/// + 由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
|
||||
/// * **提示:**
|
||||
/// * 给定链表的结点数介于 `1` 和 `100` 之间。
|
||||
/// * Related Topics
|
||||
/// + 链表
|
||||
/// + 双指针
|
||||
///
|
||||
/// * 👍 432
|
||||
/// * 👎 0
|
||||
pub fn middle_node(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
|
||||
let (mut slow, mut fast) = (&head, &head);
|
||||
while fast.as_ref().is_some() && fast.as_ref()?.next.is_some() {
|
||||
slow = &slow.as_ref()?.next;
|
||||
fast = &fast.as_ref()?.next.as_ref()?.next;
|
||||
}
|
||||
slow.clone()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::Solution;
|
||||
use crate::structure::ListNode;
|
||||
|
||||
#[test]
|
||||
fn test_q0876() {
|
||||
let list = Some(Box::new(ListNode { val: 1, next:
|
||||
Some(Box::new(ListNode { val: 3, next:
|
||||
Some(Box::new(ListNode { val: 5, next:
|
||||
Some(Box::new(ListNode { val: 7, next:
|
||||
Some(Box::new(ListNode { val: 9, next: None })) })) })) })) }));
|
||||
let option = Solution::middle_node(list);
|
||||
assert_eq!(option.unwrap().val, 5);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue