1、合并两个有序链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode();
ListNode temp = head;
while(true){
if(list1 == null && list2 == null) break;
ListNode cur = null;
if(list1!=null && list2!=null) cur = list1.val>list2.val?list2:list1;
if(list1==null || list2==null) cur = list1==null?list2:list1;
temp.next = cur;
temp = temp.next;
if(cur == list1) list1 = list1.next;
if(cur == list2) list2 = list2.next;
}
return head.next;
}
}
2、合并k个有序链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode head = new ListNode(); //虚拟头部
ListNode temp = head;
while(true){
// 找到最小值
ListNode cur = null;
for(int i=0; i<lists.length; i++){ // 遍历所有链表的记录结点,找到一个非空的记录节点
if(lists[i] != null) {
cur = lists[i];
break;
}
}
if(cur == null) break; // 如果所有记录结点都是空值,表明已经将所有结点用完,直接退出循环
for(int i=0; i<lists.length; i++){ // 遍历所有记录结点,找到所有非空记录节点的最小值结点
if(lists[i] != null && lists[i].val<cur.val) {
cur = lists[i]; // 找到最小值
}
}
// 将最小值记录结点连接到新链表尾部
temp.next = cur;
temp = temp.next;
for(int i=0; i<lists.length; i++){
if(cur == lists[i]) {
lists[i] = lists[i].next; // 将最小值记录结点往后移
}
}
}
return head.next;
}
}