版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。
難度:容易
要求:
將兩個(gè)排序鏈表合并為一個(gè)新的排序鏈表
樣例
給出 1->3->8->11->15->null,2->null, 返回1->2->3->8->11->15->null。
思路:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode result = new ListNode(0);
ListNode tmp = result;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
tmp.next = l1;
l1 = l1.next;
}else if(l1.val > l2.val){
tmp.next = l2;
l2 = l2.next;
}else{
tmp.next = l1;
l1 = l1.next;
tmp = tmp.next;
tmp.next = l2;
l2 = l2.next;
}
tmp = tmp.next;
}
if(l1 != null){
tmp.next = l1;
}
if(l2 != null){
tmp.next = l2;
}
return result.next;
}