《劍指offer》合併兩個排序的鏈表

注:此博客不再更新,所有最新文章將發表在個人獨立博客limengting.site。分享技術,記錄生活,歡迎大家關注

題目描述
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。

遞歸版:

/*
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;
        }
    }
}

非遞歸版:(外排)

需要注意如何處理頭結點爲空的情況

/*
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 res = null;
        ListNode cur = res;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                if (res == null) {
                    res = list1;
                    cur = list1;
                } else {
                    cur.next = list1;
                    cur = cur.next; // 把下一個節點作爲下一次的當前節點
                }
                list1 = list1.next;
            } else {
                if (res == null) {
                    res = list2;
                    cur = list2;
                } else {
                    cur.next = list2;
                    cur = cur.next; // 把下一個節點作爲下一次的當前節點
                }
                list2 = list2.next;
            }
        }
        // list1沒越界, list2必越界
        if (list1 != null) {
            cur.next = list1;
        }
 
        // list2沒越界,list1必越界
        if (list2 != null) {
            cur.next = list2;
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章