合并有序链表

 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值