《劍指offer》之合併兩個排序的鏈表
題目:輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。
分析:要實現兩個已經排序好的鏈表的合併,其實就是需要逐一比較鏈表中的值,然後進行合併。同時需要注意兩個列表爲空的情況。思路如圖所示:
解決方案:
-
非遞歸實現:
代碼:
public ListNode Merge(ListNode list1,ListNode list2) { // 防止list1和list2爲空的情況 if(list1 == null){ return list2; } if(list2 == null){ return list1; } // 新的鏈表 ListNode result = null; // 新的鏈表的指針 ListNode current = null; while(list1!=null && list2!=null){ if(list1.val <= list2.val){ // 第一次遍歷頭結點爲空時 if(result == null){ result = current = list1; }else{ // 將較小值追加至新的鏈表的尾部 current.next = list1; // 向後移動指針 current = list1; } list1 = list1.next; }else{ if(result == null){ result = current = list2; }else{ current.next = list2; current = list2; } list2 = list2.next; } } // 當list1和list2不等長時,直接將對於部分追加至鏈表尾部 if(list1 == null){ current.next = list2; }else{ current.next = list1; } return result; }
測試性能分析:
運行時間:22ms 佔用內存:9272k
-
遞歸實現:
代碼:
public ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null){ return list2; } if(list2 == null){ return list1; } ListNode listNode; if(list1.val<list2.val){ listNode = list1; listNode.next = Merge(list1.next,list2); }else{ listNode = list2; listNode.next = Merge(list1,list2.next); } return listNode; }
測試性能分析:
運行時間:32ms 佔用內存:9508k