合并两个排序的链表

描述

输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
 
数据范围: 0n1000,10001000
要求:空间复杂度 O(1),时间复杂度 Ο(n)
 
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6},转换过程如下图所示:
 
或输入{-1,2,4},{1,3,4}时,合并后的链表为{-1,1,2,3,4,4},所以对应的输出为{-1,1,2,3,4,4},转换过程如下图所示:

方式一:借助数组排序重组链表

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        ArrayList<Integer> list = new ArrayList<Integer>();
        while(list1!=null){
            list.add(list1.val);
            list1=list1.next;
        }
        while(list2!=null){
            list.add(list2.val);
            list2=list2.next;
        }
        Collections.sort(list);
        ListNode resultN = new ListNode(list.get(0));
        ListNode n=resultN;
        for(int i=1;i<list.size();i++){
            ListNode nextN = new ListNode(list.get(i));
            n.next=nextN;
            n=nextN;
        }
        return resultN;
    }
}

方式二:迭代

/*
 public class ListNode {
     int val;
     ListNode next = null;
 
     ListNode(int val) {
         this.val = val;
     }
 }*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        ListNode resultN = new ListNode(-1000);
        ListNode newN = resultN;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                newN.next = list1;
                list1 = list1.next;
            } else {
                newN.next = list2;
                list2 = list2.next;
            }
            newN = newN.next;
        }
        newN.next = list1 == null ? list2 : list1;
        return resultN.next;
    }
}

 方式三:递归

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        if(list1.val<list2.val){
            list1.next = Merge(list1.next, list2);
            return list1;
        } else {
            list2.next = Merge(list1, list2.next);
            return list2;
        }
    }
}
posted @ 2021-12-09 11:33  始是逍遥人  阅读(38)  评论(0编辑  收藏  举报