|
| 1 | +/** |
| 2 | + * [86] Partition List |
| 3 | + * |
| 4 | + * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. |
| 5 | + * |
| 6 | + * You should preserve the original relative order of the nodes in each of the two partitions. |
| 7 | + * |
| 8 | + * Example: |
| 9 | + * |
| 10 | + * |
| 11 | + * Input: head = 1->4->3->2->5->2, x = 3 |
| 12 | + * Output: 1->2->2->4->3->5 |
| 13 | + * |
| 14 | + * |
| 15 | + */ |
| 16 | +pub struct Solution {} |
| 17 | +use super::util::linked_list::{ListNode, to_list}; |
| 18 | + |
| 19 | +impl Solution { |
| 20 | + pub fn partition(head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> { |
| 21 | + let mut lower = Some(Box::new(ListNode::new(0))); |
| 22 | + let mut higher = Some(Box::new(ListNode::new(0))); |
| 23 | + let mut lower_tail = lower.as_mut(); |
| 24 | + let mut higher_tail = higher.as_mut(); |
| 25 | + let mut head = head; |
| 26 | + while let Some(mut inner) = head { |
| 27 | + let mut next = inner.next.take(); |
| 28 | + if inner.val < x { |
| 29 | + lower_tail.as_mut().unwrap().next = Some(inner); |
| 30 | + lower_tail = lower_tail.unwrap().next.as_mut(); |
| 31 | + } else { |
| 32 | + higher_tail.as_mut().unwrap().next = Some(inner); |
| 33 | + higher_tail = higher_tail.unwrap().next.as_mut(); |
| 34 | + } |
| 35 | + head = next |
| 36 | + } |
| 37 | + lower_tail.as_mut().unwrap().next = higher.unwrap().next.take(); |
| 38 | + lower.unwrap().next.take() |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// submission codes end |
| 43 | + |
| 44 | +#[cfg(test)] |
| 45 | +mod tests { |
| 46 | + use super::*; |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn test_86() { |
| 50 | + assert_eq!( |
| 51 | + Solution::partition(linked![1,4,3,2,5,2], 3), |
| 52 | + linked![1,2,2,4,3,5] |
| 53 | + ); |
| 54 | + assert_eq!( |
| 55 | + Solution::partition(linked![1,4,3,2,5,2], 8), |
| 56 | + linked![1,4,3,2,5,2] |
| 57 | + ); |
| 58 | + assert_eq!( |
| 59 | + Solution::partition(linked![], 0), |
| 60 | + linked![] |
| 61 | + ); |
| 62 | + } |
| 63 | +} |
0 commit comments