您的位置:首页 > 其它

Merge Two Sorted Lists

2014-08-02 17:19 190 查看
问题:有序合并两个有序链表
分析:归并排序的合并部分

class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *helper=new ListNode(0);
ListNode *head=helper;
while(l1 && l2)
{
if(l1->val<l2->val) helper->next=l1,l1=l1->next;
else helper->next=l2,l2=l2->next;
helper=helper->next;
}
if(l1) helper->next=l1;
if(l2) helper->next=l2;
return head->next;
}
};


  javascript

/**
* 题意:合并两条有序的链表
* 分析:归并排序的链表形式
* Definition for singly-linked list.
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
var head = null,iCur = null;
if(l1.val<l2.val){
iCur = l1;
l1 = l1.next;
}
else {
iCur = l2;
l2 = l2.next;
}
head = iCur;
while(l1!=null && l2!=null){
if(l1.val < l2.val) {
iCur.next = l1;
l1 = l1.next;
}else{
iCur.next = l2;
l2 = l2.next;
}
iCur = iCur.next;
}
if(l1 == null) iCur.next = l2;
if(l2 == null) iCur.next = l1;
return head;
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: