leetcode------链表4

一、合并两个升序链表:

思路:
1、定义一个head头指针,用来指向合并后的链表;
2、同时遍历l1, l2 并且比较两个链表的第一个节点,将head指向其中最小节点,同时将较小链表的指针下移一位;(例如:l1<l2 ,head.next = l1 , l1 = l2.next);
3、如果l1或者l2有一个遍历完,则将没遍历完的链表接在最终的链表后面;

public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
}

public ListNode mergeTwoList(ListNode l1,ListNode l2){
       ListNode head = new ListNode();
       ListNode new_head = head;
       while(l1 != null && l2 != null){
           if(l1.val <l2.val){
               head.next = l1;
               l1 = l1.next;
           }else{
               head.next = l2;
               l2 = l2.next;
           }
           head = head.next;
       }
       if(l1 == null){
           head.next = l2;
       }
       if(l2 == null){
           head.next = l1;
       }
       return new_head.next;
   }

二、合并k个升序链表

思路:分而治之,将链表数组分成两份,然后分别去合并,如果分组后依然链表数组的长度依然大于2,继续分组合并。使用递归的思想:

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) {
        if(lists == null){
            return null;
        }
        if(lists.length == 1){
            return lists[0];
        }
        if(lists.length == 2){
            return mergeTwoList(lists[0],lists[1]);
        }
        int mid = lists.length/2;

        ListNode[] sub_list1 = new ListNode[mid+1];
        ListNode[] sub_list2 = new ListNode[mid+1];
        int count=0;
        for(int i=0;i<mid;i++){
            sub_list1[count++] =lists[i]; 
        }
        count = 0;
        for(int i=mid;i<lists.length;i++){
            sub_list2[count++] = lists[i];
        }
        ListNode l1 = mergeKLists(sub_list1);
        ListNode l2 = mergeKLists(sub_list2);

        return mergeTwoList(l1,l2);

    }
    public ListNode mergeTwoList(ListNode l1,ListNode l2){
        ListNode head = new ListNode();
        ListNode new_head = head;
        while(l1 != null && l2 != null){
            if(l1.val <l2.val){
                head.next = l1;
                l1 = l1.next;
            }else{
                head.next = l2;
                l2 = l2.next;
            }
            head = head.next;
        }
        if(l1 == null){
            head.next = l2;
        }
        if(l2 == null){
            head.next = l1;
        }
        return new_head.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值