rust编程-链表:使用struct实现链表,使用堆合并k个升序链表,自定义Display

此处代码中的链表不是泛型,还没有找到泛型实现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 = &currentNode.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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值