|
@@ -0,0 +1,50 @@
|
|
|
|
+use crate::solutions::ListNode;
|
|
|
|
+
|
|
|
|
+struct Solution;
|
|
|
|
+impl Solution {
|
|
|
|
+ pub fn insertion_sort_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
|
|
|
|
+ let mut head = head;
|
|
|
|
+ let mut result = None;
|
|
|
|
+ while let Some(mut node) = head {
|
|
|
|
+ let next = node.next.take();
|
|
|
|
+ result = Solution::helper(result, node);
|
|
|
|
+ head = next;
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ result
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ fn helper(head: Option<Box<ListNode>>, mut node: Box<ListNode>) -> Option<Box<ListNode>> {
|
|
|
|
+ match head {
|
|
|
|
+ None => Some(node),
|
|
|
|
+ Some(item_node) if item_node.val > node.val => {
|
|
|
|
+ node.next = Some(item_node);
|
|
|
|
+ Some(node)
|
|
|
|
+ },
|
|
|
|
+ Some(mut item_node) => {
|
|
|
|
+ let next = item_node.next.take();
|
|
|
|
+ item_node.next = Solution::helper(next, node);
|
|
|
|
+ Some(item_node)
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+#[cfg(test)]
|
|
|
|
+mod tests {
|
|
|
|
+ use super::*;
|
|
|
|
+ use crate::solutions::{to_list, to_vec};
|
|
|
|
+
|
|
|
|
+ #[test]
|
|
|
|
+ fn test_insertion_sort_list() {
|
|
|
|
+ let nums = vec![4,2,1,3];
|
|
|
|
+ let head = to_list(nums);
|
|
|
|
+
|
|
|
|
+ let res = Solution::insertion_sort_list(head);
|
|
|
|
+ assert_eq!(to_vec(res), vec![1,2,3,4]);
|
|
|
|
+ }
|
|
|
|
+}
|