LeetCode刷题之第23题

前言:

这道题也就是LeetCode每日一题活动的4月26日的那一题

题目描述:

在这里插入图片描述

题目分析:

这道题最核心的应该是要想到两条有序链合并的情况,只要了解两条有序链合并的情况,这道题就很好解决了。

代码:

public class MergeKLists {
    public static void main(String[] args) {
        ListNode[] lists = new ListNode[3];
        lists[0] = new ListNode(1);
        lists[0].next = new ListNode(4);
        lists[0].next.next = new ListNode(5);

        lists[1] = new ListNode(1);
        lists[1].next = new ListNode(3);
        lists[1].next.next = new ListNode(4);

        lists[2] = new ListNode(2);
        lists[2].next = new ListNode(6);

        ListNode head = mergeKLists(lists);
        while (head!=null){
            System.out.print(head.val+"->");
            head = head.next;
        }
    }

    public static ListNode mergeKLists(ListNode[] lists) {
        int len = lists.length;
        if (len==0)
            return null;
        if (len==1)
            return lists[0];
        for (int i = 0; i < len-1; i++) {
            lists[i+1] = mergeTwoLink(lists[i],lists[i+1]);
        }
        return lists[len-1];
    }

    private static ListNode mergeTwoLink(ListNode list, ListNode list1) {
        ListNode p = list;    //初始化第一条链的指针
        ListNode q = list1;   //初始化第二条链的指针
        //ListNode head = new ListNode(list.val<list1.val?list.val:list1.val);   //初始化头指针
        ListNode head = new ListNode(0);   //随机初始化一个头,后期将该指针向后移一位即可
        ListNode node = head;           //用来遍历形成链的节点指针
        while (p!=null&&q!=null){
            if (p.val<q.val){
                node.next=p;
                node = node.next;
                p = p.next;
            }else {
                node.next = q;
                node = node.next;
                q = q.next;
            }
        }
        if (p!=null){
            node.next = p;
        }
        if (q!=null){
            node.next = q;
        }
        head = head.next;
        return head;
    }
}

结果显示:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值