劍指offer -合併兩個排序鏈表

題目描述:

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

主要思想 :

在這裏插入圖片描述

  public static ListNode Merge(ListNode list1, ListNode list2) {
        ListNode head = null;
        if (list1 == null && list2 == null)
            return head;
        if (list1.val <= list1.val) {
            head = list1;
            list1 = list1.next;
        } else {
            head = list2;
            list2 = list2.next;
        }
        ListNode P = head;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                P.next = list1;
                P = P.next;
                list1 = list1.next;
            } else {
                P.next = list2;
                P = P.next;
                list2 = list2.next;
            }
        }
        if (list1 != null) {
            P.next = list1;
        }
        if (list2 != null) {
            P.next = list2;
        }
        return head;
    }

注意點:

  • 判斷兩個鏈表均爲空時,返回null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章