lintcode 165 合并两个排序链表

来源:互联网 发布:网络硬盘录像机 交换机 编辑:程序博客网 时间:2024/05/18 21:08

1.将两个排序链表合并为一个新的排序链表

2.遍历两个链表的公共长度,根据节点值的大小来改变每次节点的连接,然后判断哪条链表还有剩余,最后将较长链表的剩余部分追加到节点的后面

3.

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @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
     */
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
         ListNode *dummy=new ListNode(0);
        ListNode *temp=dummy;
        while(l1&&l2)
        {
            if(l1->val<=l2->val){temp->next=l1;l1=l1->next;temp=temp->next;}
            else{temp->next=l2;l2=l2->next;temp=temp->next;}
        }
        if(l1!=NULL){temp->next=l1;}
        else {temp->next=l2;}
        return dummy->next;
    }
};

4.感想

类似于插入排序(同学给我讲的),难点在于分情况时的考虑和处理。

0 0
原创粉丝点击