题目
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
解题思路
- 对每个链表的首节点进行比较,获取当前的最小节点;
- 将每个阶段的最小节点进行链接;
代码展示
class Solution { public ListNode mergeKLists(ListNode[] lists) { ListNode head = null; ListNode result = null; int count = 0; while (count < lists.length){ count = 0; //获取首节点 if(head == null){ int min = Integer.MAX_VALUE; int index = 0; for (int i = 0; i < lists.length; i++){ if(lists[i] == null){ count++; continue; } int temp = lists[i].val; if(temp < min){ min = temp; head = lists[i]; index = i; } } if(lists[index] != null) { lists[index] = lists[index].next; } result = head; } else { int min = Integer.MAX_VALUE; int index = 0; for (int i = 0; i < lists.length; i++){ if(lists[i] == null){ count++; continue; } int temp = lists[i].val; if(temp < min){ min = temp; result.next = lists[i]; index = i; } } if(lists[index] != null) { lists[index] = lists[index].next; } result = result.next; } } return head; } }