題目
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
即合併兩個有序鏈表。有兩種解法。
第一種
用遞歸的思想。
1. 每次遞歸返回較小的那個節點。並且該節點的下一個指向下一次遞歸返回的節點。這次返回的節點會被上一次遞歸的節點連接上。
2. 當某個節點爲null時,說明該節點所在的鏈表已經被遍歷完了。直接返回另一個鏈表。
public ListNode merge(ListNode l1,ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = merge(l1.next,l2);
return l1;
}else{
l2.next = merge(l1,l2.next);
return l2;
}
}
第二種
用普通遍歷的方法。用兩個指針分貝記錄遍歷鏈表所在的位置,以其中一條鏈表爲基準,例如L1,比較兩個
節點,若l1小於l2,則L1往下移,若l1>L2,則將l2指向的節點插入l1。代碼如下。
public ListNode merge(ListNode l1, ListNode l2)
{
ListNode dummy = new ListNode(0);
dummy.next = l1;
ListNode cur = dummy;
while(l1!=null && l2!=null)
{
if(l1.val<l2.val)
{
l1 = l1.next;
}
else
{
ListNode next = l2.next;
cur.next = l2;
l2.next = l1;
l2 = next;
}
cur = cur.next;
}
if(l2!=null)
cur.next = l2;
return dummy.next;
}