此处代码中的链表不是泛型,还没有找到泛型实现Display的方法。。。
use chrono::{DateTime, Utc};
use chrono::prelude::*;
use chrono::offset::LocalResult;
use std::cmp::{Ord, Ordering, PartialEq};
use std::collections::BinaryHeap;
use std::fmt::{self, Formatter, Display};
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}
impl ListNode {
#[inline]
fn new(value: i32) -> Self {
ListNode {
next: None,
val :value
}
}
}
impl Ord for ListNode {
fn cmp(&self, other: &Self) -> Ordering {
// 默认是最大堆,这里颠倒顺序,实现最小堆。
other.val.cmp(&self.val)
}
}
impl PartialOrd for ListNode {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Display for ListNode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f,"{}\n",self.val);
let mut pNode = &self.next;
while let Some(currentNode) = pNode{
write!(f,"{}\n",currentNode.val);
pNode = ¤tNode.next;
}
write!(f,"==============end")
}
}
pub fn merge_k_lists(lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
if lists.is_empty() {
return None;
}
let mut ans = Box::new(ListNode::new(0));
let mut ptr = &mut ans;
let mut heap = BinaryHeap::new();
// 把第一列的元素放到堆里。
for node in lists {
if let Some(n) = node {
heap.push(n);
}
}
// 弹出最小的,然后把它剩下的再加入到堆中。
while let Some(mut node) = heap.pop() {
if let Some(next) = node.next.take() {
heap.push(next);
}
ptr.next = Some(node);
ptr = ptr.next.as_mut().unwrap();
}
ans.next
}
fn main()
{
let a = ListNode::new(4);
let b = ListNode{
val : 2,
next : Some(Box::new(a)),
};
let c = ListNode{
val : 1,
next : Some(Box::new(b)),
};
let a0 : ListNode = ListNode::new(5);
let b0 = ListNode{
val : 3,
next : Some(Box::new(a0)),
};
let c0 = ListNode{
val : 1,
next : Some(Box::new(b0)),
};
let lists = vec![Some(Box::new(c)),Some(Box::new(c0))];
let result = merge_k_lists(lists);
println!("{:?}",&result);
if let Some(node) = result{
println!("{}",node);
}
}
输出为:
Some(ListNode { val: 1, next: Some(ListNode { val: 1, next: Some(ListNode { val: 2, next: Some(ListNode { val: 3, next: Some(ListNode { val: 4, next: Some(ListNode { val: 5, next: None }) }) }) }) }) })
1
1
2
3
4
5
==============end