use std::fmt::{self, Display};
#[derive(Debug)]
struct ListNode {
val: i32,
next: Option<Box<ListNode>>,
}
impl ListNode {
fn new(val: i32) -> Self {
ListNode { val, next: None }
}
}
struct LinkedList {
head: Option<Box<ListNode>>,
}
impl LinkedList {
fn new() -> Self {
LinkedList { head: None }
}
fn push(&mut self, val: i32) {
let new_node = Box::new(ListNode { val, next: self.head.take() });
self.head = Some(new_node);
}
fn merge_sort(&mut self) {
self.head = Self::merge_sort_list(self.head.take());
}
fn merge_sort_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
// Base case: empty or single node
if head.is_none() || head.as_ref().unwrap().next.is_none() {
return head;
}
// Split list into two halves
let (left, right) = Self::split(head);
// Recursively sort each half
let sorted_left = Self::merge_sort_list(left);
let sorted_right = Self::merge_sort_list(right);
// Merge sorted halves
Self::merge(sorted_left, sorted_right)
}
fn split(mut head: Option<Box<ListNode>>) -> (Option<Box<ListNode>>, Option<Box<ListNode>>) {
if head.is_none() || head.as_ref().unwrap().next.is_none() {
return (head, None);
}
let mut slow = head.as_mut();
let mut fast = head.as_ref().unwrap().next.as_ref();
while fast.is_some() && fast.unwrap().next.is_some() {
fast = fast.unwrap().next.as_ref().unwrap().next.as_ref();
slow = slow.unwrap().next.as_mut();
}
let mid = slow.unwrap().next.take();
(head, mid)
}
fn merge(
list1: Option<Box<ListNode>>,
list2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
match (list1, list2) {
(None, None) => None,
(Some(node), None) | (None, Some(node)) => Some(node),
(Some(mut node1), Some(mut node2)) => {
if node1.val < node2.val {
let next = node1.next.take();
node1.next = Self::merge(next, Some(node2));
Some(node1)
} else {
let next = node2.next.take();
node2.next = Self::merge(Some(node1), next);
Some(node2)
}
}
}
}
fn print(&self) {
let mut curr = self.head.as_ref();
while let Some(node) = curr {
print!("{} -> ", node.val);
curr = node.next.as_ref();
}
println!("null");
}
}
fn main() {
let mut list = LinkedList::new();
// Push elements in reverse order to create 4 -> 2 -> 1 -> 3
list.push(3);
list.push(1);
list.push(2);
list.push(4);
println!("Original list:");
list.print();
list.merge_sort();
println!("Sorted list:");
list.print();
}
if head.is_none() || head.as_ref().unwrap().next.is_none() { return head; }
Base case: stop recursion when list is empty or has one node
let (left, right) = Self::split(head);
Split list into two halves using slow and fast pointers
let sorted_left = Self::merge_sort_list(left);
Recursively sort left half
let sorted_right = Self::merge_sort_list(right);
Recursively sort right half
Self::merge(sorted_left, sorted_right)
Merge two sorted halves into one sorted list
if node1.val < node2.val { ... } else { ... }
Compare nodes to merge in sorted order
Original list:
4 -> 2 -> 1 -> 3 -> null
Sorted list:
1 -> 2 -> 3 -> 4 -> null