java将所有链表合并到一个升序链表中,返回合并后的链表

优秀算法:

1、题目简介:

/**
 * 给你一个链表数组,每个链表都已经按升序排列。
 *
 * 请你将所有链表合并到一个升序链表中,返回合并后的链表。
 * 示例 1:
 *
 * 输入:lists = [[1,4,5],[2,3,4],[5,6]]
 * 输出:[1,2,3,4,4,5,5,6]
 * 解释:链表数组如下:
 * [
 *   1->4->5,
 *  2->3->4,
 *   5->6
 * ]
 * 将它们合并到一个有序链表中得到。
 * 1->2->3->4->4->5->5->6
 */

2、解题思路:

采用小顶堆思想,每次都是弹出最小的,然后放到链表里。

3、核心代码演示:

public class MergeNodeLists {

	public static void main(String[] args) {
		int[] a = {1,4,5};
		int[] b = {2,3,4};
		int[] c = {5,6};

		ListNode nodeA = createNode(a);
		ListNode nodeB = createNode(b);
		ListNode nodeC = createNode(c);
		 

		ListNode[] lists = {nodeC,nodeA,nodeB};
		//ListNode node = mergeKLists(lists);
		ListNode node = mergeKLists1(lists);

		while (node != null){
			System.out.print(node.val + " ");

			node = node.next;
		}
		System.out.println();

	}

    //创建链表
	private static ListNode createNode(int[] a) {
		ListNode head = new ListNode();
		head.val = a[0];
		ListNode cur = head;
		for(int i = 1;i < a.length;i++){
			ListNode node = new ListNode();
			node.val = a[i];
			cur.next  = node;
			cur = cur.next;
		}
		return head;
	}


	public static class ListNode {
		public int val;
		public ListNode next;
	}
    
    //指定比较器comparator
	public static class ListNodeComparator implements Comparator<ListNode> {

		@Override
		public int compare(ListNode o1, ListNode o2) {
			return o1.val - o2.val;
		}

	}

    //合并多个链表
	public static ListNode mergeKLists(ListNode[] lists) {
		if (lists == null) {
			return null;
		}
		//https://blog.csdn.net/u010853261/article/details/78520960  小顶堆。小堆堆要求根节点的关键字既小于或等于左子树的关键字值,又小于或等于右子树的关键字值。
		PriorityQueue<ListNode> heap = new PriorityQueue<>(new ListNodeComparator());
		for (int i = 0; i < lists.length; i++) {
			if (lists[i] != null) {
				heap.add(lists[i]);
			}
		}
		if (heap.isEmpty()) {
			return null;
		}
		ListNode head = heap.poll();
		ListNode pre = head;
		if (pre.next != null) {
			heap.add(pre.next);
		}
		while (!heap.isEmpty()) {
			ListNode cur = heap.poll();
			pre.next = cur;
			pre = cur;
			if (cur.next != null) {
				heap.add(cur.next);
			}
		}
		return head;
	}

}

这是其中一个思路分享,大家一定学会举一反三,多多练习!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值