给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
这个问题,我个人有两种解法,一种是根据归并排序的思想,每两个有序链表进行合并,最终合并为,一个最大的有序链表;还有一种解法是利用PriorityQueue做,可以建立一个小根堆,和一个傀儡头节点,每次将最小的链表取出, 将最小链表的头结点放到傀儡链表中,并且判断当前节点的下一个是否为空,若不为空,就将它的下一个节点作为头结点放进优先级队列中去,若为空,就不用放了。
分治思想
public ListNode merge(ListNode l ,ListNode r){
ListNode tmp = new ListNode(-1);
ListNode tCur = tmp;
while(l != null && r != null){
if(l.val <= r.val){
tCur.next = l;
l = l.next;
}else{
tCur.next = r;
r = r.next;
}
tCur = tCur.next;
}
while(l != null){
tCur.next = l;
l = l.next;
tCur = tCur.next;
}
while(r != null ){
tCur.next = r;
r = r.next;
tCur = tCur.next;
}
return tmp.next;
}
public ListNode div(ListNode[] lists, int left ,int right ){
if(left >= right){
return lists[left];
}
int mid = (left+right) /2 ;
ListNode l = div(lists, left,mid);
ListNode r = div(lists, mid+1,right);
return merge(l,r);
}
优先级队列思想
PriorityQueue<ListNode> q = new PriorityQueue<>((o1,o2)->{return o1.val - o2.val;});
for(int i = 0 ; i < lists.length ; i++ ){
if(lists[i] != null){
q.offer(lists[i]);
}
}
ListNode tmp = new ListNode(-1);
ListNode tCur = tmp;
while(!q.isEmpty()){
ListNode node = q.poll();
tCur.next = node;
tCur = tCur.next;
if(node.next != null){
node = node.next;
q.offer(node);
}
}