LeetCode-21-連結串列-合併兩個有序連結串列
阿新 • • 發佈:2018-12-15
將兩個有序連結串列合併為一個新的有序連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
方案一:歸併中的merge方法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { //定義新連結串列頭 ListNode temp = new ListNode(0); //定義三個連結串列的移動指標 ListNode current1=l1; ListNode current2=l2; ListNode current3=temp; int t=0; while(current1 !=null && current2 !=null){ if(current1.val < current2.val){ current3.next=current1; current3 = current3.next; current1=current1.next; }else{ current3.next=current2; current3 = current3.next; current2=current2.next; } } //l2排完,l1未排完 while(current1 !=null){ current3.next=current1; current3 = current3.next; current1=current1.next; } while(current2 !=null){ current3.next=current2; current3 = current3.next; current2=current2.next; } return temp.next; } }
方案二:遞迴
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1==null){ return l2; } if(l2==null){ return l1; } ListNode mergeNode; if(l1.val<l2.val){ mergeNode = l1; mergeNode.next = mergeTwoLists(l1.next,l2); }else{ mergeNode = l2; mergeNode.next = mergeTwoLists(l1,l2.next); } return mergeNode; }