劍指Offer-合併兩個排序的鏈表Java

16、合併兩個排序的鏈表

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

思路:
遞歸。

/*
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) {
        //list1和list2都作爲移動指針在原鏈表中比較節點值大小
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        ListNode mergeHead = null;//新表頭
        ListNode current = null;//移動指針
        while(list1!=null && list2!=null){
            if(list1.val <= list2.val){
                if(mergeHead == null){//處理新鏈表頭節點
                   mergeHead = current = list1;
                }else{
                   current.next = list1;
                   current = current.next;
                }
                list1 = list1.next;
            }else{
                if(mergeHead == null){//處理新鏈表頭節點
                   mergeHead = current = list2;
                }else{
                   current.next = list2;
                   current = current.next;
                }
                list2 = list2.next;
            }
        }
        if(list1 == null){//list1爲空,將list2剩餘節點全部接上
            current.next = list2;
        }else{//list2爲空,將list1剩餘節點全部接上
            current.next = list1;
        }
        return mergeHead;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章