leetcode/
odd_even_linked_list.rs1use crate::ListNode;
31
32pub struct Solution;
33
34impl Solution {
35 pub fn odd_even_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
36 let mut even_head = None;
37 let mut even_tail = &mut even_head;
38
39 let mut p = &mut head;
40 while let Some(node) = p {
41 if let Some(mut even) = node.next.take() {
42 node.next = even.next.take();
43 *even_tail = Some(even);
44 even_tail = &mut even_tail.as_mut().unwrap().next;
45 }
46
47 if node.next.is_some() {
48 p = &mut node.next;
49 } else {
50 node.next = even_head;
52 break;
53 }
54 }
55
56 head
57 }
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63 use crate::list;
64
65 #[test]
66 fn test() {
67 let cases = vec![
68 (vec![1,3,5,2,4], list![1,2,3,4,5]),
69 (vec![2,3,6,7,1,5,4], list![2,1,3,5,6,4,7]),
70 (vec![], list![]),
71 ];
72 let t = |v| ListNode::into_vec(Solution::odd_even_list(v));
73 for (expect, input) in cases {
74 assert_eq!(expect, t(input));
75 }
76 }
77}