剑指offer13-合并两个排序的链表

234 阅读1分钟

合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路1

  • 迭代
程序(java)
    /**
     * code1
     * 时间复杂度:O(m+n)
     *空间复杂度:O(1)
     * 
     */
    public static ListNode Merge(ListNode list1, ListNode list2) {
        ListNode preHead = new ListNode(-1);
        ListNode pre = preHead;
        
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                pre.next = list1;
                list1 = list1.next;
            } else {
                pre.next = list2;
                list2 = list2.next;
            }
            pre = pre.next;
        }

        pre.next = list1 == null ? list2 : list1;
        return preHead.next;
    }
     /**
     * code2
     * 时间复杂度:O(m+n)
     * 时间复杂度:O(1)
     * 
     */
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1==null){
            return list2;
        }
        if(list2==null){
            return list1;
        }
        ListNode pre = null;
        ListNode now = list1;
        while(list2!=null&&now!=null){
            if(list2.val<=now.val){
                ListNode temp=list2;
                list2=list2.next;
                if(pre!=null){
                    pre.next=temp;
                }else{
                    list1=temp;
                }
                temp.next=now;
                pre=temp;
            }else{
                pre=now;
                now=now.next;
            }
        }
        if(now==null){
            pre.next=list2;
        }
        return list1;
    }
}
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/

思路2

  • 递归

程序(java)
     /**
     * code3
     * 时间复杂度:O(m+n)
     * 时间复杂度:O(1)
     * 
     */
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode mergeHead = null;
        if (list1.val < list2.val) {
            mergeHead=list1;
            mergeHead.next = Merge(list1.next, list2);
        } else {
            mergeHead=list2;
            mergeHead.next = Merge(list1, list2.next);
        }
        return mergeHead;
    }
}
     /**
     * code4
     * 时间复杂度:O(m+n)
     * 时间复杂度:O(1)
     * 
     */
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;
        }
    }
}