ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

合并两个有序链表_21

2022-04-13 10:04:18  阅读:186  来源: 互联网

标签:ListNode 21 list1 lists list2 链表 有序 null


21. 合并两个有序链表:https://leetcode-cn.com/problems/merge-two-sorted-lists/
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummyHead = new ListNode(0);
        ListNode head = dummyHead;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                head.next = list1;
                list1 = list1.next;
            } else {
                head.next = list2;
                list2 = list2.next;
            }
            head =  head.next;
        }
        head.next = list1 == null ? list2 : list1;
        return dummyHead.next;
    }
}

23. 合并K个升序链表
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        return merge(lists, 0, lists.length-1);
    }

    public ListNode merge(ListNode[] lists, int l, int r){
        if(l == r) {     
            return lists[l];    
        }
        if(l > r)  {     
            return null;        
        }
        int mid = (l + r) >> 1;
        return mergerTwoLists(merge(lists, l, mid), merge(lists, mid+1, r));
    }

    public ListNode mergerTwoLists(ListNode l1, ListNode l2){
        ListNode dummy = new ListNode(0);
        ListNode prev = dummy;
        while(l1 != null && l2 != null) {
            int x = l1 == null ? 0: l1.val;
            int y = l2 == null ? 0: l2.val;
            if(x <= y){
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }
        prev.next = l1 == null ? l2: l1;
        return dummy.next;
    }
}

 

标签:ListNode,21,list1,lists,list2,链表,有序,null
来源: https://www.cnblogs.com/pfzhang18/p/16138869.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有