147. Insertion Sort List Medium

@problem@discussion
#Linked List#Sorting



1/**
2 * [147] Insertion Sort List
3 *
4 * Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
5 * The steps of the insertion sort algorithm:
6 * <ol>
7 * 	Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
8 * 	At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
9 * 	It repeats until no input elements remain.
10 * </ol>
11 * The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
12 * <img alt="" src="https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif" style="height:180px; width:300px" />
13 *  
14 * Example 1:
15 * <img alt="" src="https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg" style="width: 422px; height: 222px;" />
16 * Input: head = [4,2,1,3]
17 * Output: [1,2,3,4]
18 * 
19 * Example 2:
20 * <img alt="" src="https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg" style="width: 542px; height: 222px;" />
21 * Input: head = [-1,5,3,4,0]
22 * Output: [-1,0,3,4,5]
23 * 
24 *  
25 * Constraints:
26 * 
27 * 	The number of nodes in the list is in the range [1, 5000].
28 * 	-5000 <= Node.val <= 5000
29 * 
30 */
31pub struct Solution {}
32use crate::util::linked_list::{ListNode, to_list};
33
34// problem: https://leetcode.com/problems/insertion-sort-list/
35// discuss: https://leetcode.com/problems/insertion-sort-list/discuss/?currentPage=1&orderBy=most_votes&query=
36
37// submission codes start here
38
39// Definition for singly-linked list.
40// #[derive(PartialEq, Eq, Clone, Debug)]
41// pub struct ListNode {
42//   pub val: i32,
43//   pub next: Option<Box<ListNode>>
44// }
45// 
46// impl ListNode {
47//   #[inline]
48//   fn new(val: i32) -> Self {
49//     ListNode {
50//       next: None,
51//       val
52//     }
53//   }
54// }
55impl Solution {
56    pub fn insertion_sort_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
57        Some(Box::new(ListNode::new(0)))
58    }
59}
60
61// submission codes end
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn test_147() {
69    }
70}
71


Back
© 2025 bowen.ge All Rights Reserved.