合并两个排序的链表

31 阅读1分钟

合并两个排序的链表

//写法一:
//时间复杂度:O(n)
//空间复杂度:O(n)
public ListNode Merge(ListNode list1, ListNode list2) {
    if(list1==null){
        return list2;
    }
    if(list2==null){
        return list1;
    }

    ListNode dummyHead = new ListNode(-1);
    ListNode tail = dummyHead;

    while(list1!=null && list2!=null){
        if(list1.val < list2.val){
            ListNode node = new ListNode(list1.val);
            tail.next = node;
            tail = node;
            list1 = list1.next;
        }else{
            ListNode node = new ListNode(list2.val);
            tail.next = node;
            tail = node;
            list2 = list2.next;
        }
    }

    if(list1==null){
        tail.next = list2;
    }
    if(list2==null){
        tail.next=list1;
    }
    return dummyHead.next;
}
//写法二:
//时间复杂度:O(n)
//空间复杂度:O(1)

public ListNode Merge(ListNode list1, ListNode list2) {
    if(list1==null){
        return list2;
    }
    if(list2==null){
        return list1;
    }

    ListNode dummyHead = new ListNode(-1);
    ListNode cur=dummyHead;

    while(list1!=null && list2!=null){
        if(list1.val<list2.val){
            cur.next = list1;
            list1 =list1.next;
        }else{
            cur.next=list2;
            list2=list2.next;
        }
        cur=cur.next;
    }
    if(list1!=null){
        cur.next=list1;
    }
    if(list2!=null){
        cur.next=list2;
    }
    return dummyHead.next;
}

www.mianshi.onlinewww.i9code.cn

本文由博客一文多发平台 OpenWrite 发布!