Merge Two Sorted Lists

问题:有序合并两个有序链表
分析:归并排序的合并部分

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;
}; 

  

原文地址:https://www.cnblogs.com/zsboy/p/3887229.html