Explorar o código

feat: sort_list

Zhang Li hai 11 meses
pai
achega
de26255fa9

+ 50 - 0
src/solutions/list/insertion_sort_list.rs

@@ -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]);
+    }
+}

+ 3 - 1
src/solutions/list/mod.rs

@@ -4,4 +4,6 @@ mod remove_duplicate_from_sorted_list;
 mod merge_k_sorted_lists;
 mod merge_two_sorted_lists;
 mod partition_list;
-mod reverse_linked_list2;
+mod reverse_linked_list2;
+mod insertion_sort_list;
+mod sort_list;

+ 38 - 0
src/solutions/list/sort_list.rs

@@ -0,0 +1,38 @@
+use crate::solutions::ListNode;
+struct Solution;
+impl Solution {
+    pub fn sort_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
+        let mut head = head;
+        let mut v = vec![];
+
+        while let Some(mut node) = head {
+            head = node.next.take();
+            v.push(node);
+        }
+
+        v.sort_by_key(|node| node.val);
+
+        while !v.is_empty() {
+            let mut node = v.pop().unwrap();
+            node.next = head.take();
+            head = Some(node);
+        }
+
+        head
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::solutions::{to_vec, to_list};
+
+    #[test]
+    fn test_sort_list() {
+        let nums = vec![-1, 5, 3, 4, 0];
+        let head = to_list(nums);
+        let res = Solution::sort_list(head);
+        assert_eq!(to_vec(res), vec![-1, 0, 3, 4, 5]);
+    }
+}