Skip to content

Latest commit

 

History

History
53 lines (41 loc) · 1.26 KB

partition-list.md

File metadata and controls

53 lines (41 loc) · 1.26 KB

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你应当 保留 两个分区中每个节点的初始相对位置。

示例 1:

img.png

输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2
输出:[1,2]
提示:
  • 链表中节点的数目在范围 [0, 200] 内
  • -100 <= Node.val <= 100
  • -200 <= x <= 200
题解:
impl Solution {
    pub fn partition(mut head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> {
        let mut small = Box::new(ListNode::new(-201));
        let mut large = Box::new(ListNode::new(201));
        let mut ps = small.as_mut();
        let mut pl = large.as_mut();

        while let Some(mut h) = head {
            head = h.next.take();

            if h.val < x {
                ps.next = Some(h);
                ps = ps.next.as_mut().unwrap();
            } else {
                pl.next = Some(h);
                pl = pl.next.as_mut().unwrap();
            }
        }

        ps.next = large.next;

        small.next
    }
}