【leetcode】23. Merge K Sorted Lists(JAVA)

Description:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6

题目链接

思路:
首先找出所有链表头中起始结点值最小的,然后以这个链表头所在链表为基准,将其他所有链表加进来(不分配内存,只修改链表中结点的指向)


全部代码:

package leetcode;

class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
	}
}

public class leetcode23 {
	static int a[] = {-1,-1,-1};
	static int b[]= {-2,-2,-1};
	// static int c[]= {2,6};

	static ListNode createList(int a[]) {
		if (a.length == 0)
			return null;
		ListNode phead = new ListNode(a[0]);
		ListNode p = phead;
		for (int i = 1; i < a.length; i++) {
			ListNode newnode = new ListNode(a[i]);
			p.next = newnode;
			p = p.next;
		}
		p.next = null;
		return phead;
	}

	public static void main(String[] args) {
		// create lists
		ListNode la = createList(a);
		 ListNode lb=createList(b);
		// ListNode lc=createList(c);
		ListNode lists[] = { la,lb};

		Solution s = new Solution();
		ListNode head = s.mergeKLists(lists);
		ListNode p = head;

		if (head == null)
			System.out.println("the list is empty");
		else {
			System.out.println("the whole lists:");
			System.out.printf("%d", p.val);
			p = p.next;
			while (p != null) {
				System.out.printf("--->%d ", p.val);
				p = p.next;
			}
		}
	}

}

class Solution {
	public ListNode mergeKLists(ListNode[] lists) {
//边界检查***********************
//没有链表或者只有一个链表
		if (lists.length == 0)
			return null;
		if (lists.length == 1)
			return lists[0];

//所有链表都是空的
		int start = 0;
		while (start < lists.length&&lists[start]==null)
			start++;
		if (start == lists.length)
			return null;
//边界检查结束*********************
		int i;
		
		//找到具有最小值的链表头
		int min=Integer.MAX_VALUE,startpos=0;
		for(i=0;i<lists.length;i++) {
			if(lists[i]!=null) {
				if(lists[i].val<min) {
					startpos=i;
					min=lists[i].val;
				}
			}
		}
		
		for (i = 0; i < lists.length; i++) { // 将剩下的链表依次插入
			if (lists[i] == null||i==startpos)
				continue; // 当前链表为空时,直接跳过

			ListNode p2 = lists[i];
			ListNode pnext2 = p2.next;
			ListNode p1 = lists[startpos];
			
			
			while (p2 != null) {

				while (p1.next != null && p1.next.val < p2.val)
					p1 = p1.next;
				p2.next = p1.next;
				p1.next = p2;
				p1 = p2;
				p2 = pnext2;
				if (p2 != null)
					pnext2 = pnext2.next;
			}
		}

		return lists[startpos];
	}
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/83178357