码迷,mamicode.com
首页 > 编程语言 > 详细

LintCode 合并两个排序链表

时间:2015-06-21 23:50:18      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

样例

给出 1->3->8->11->15->null2->null, 返回 1->2->3->8->11->15->null

感觉很像mergeSort

/**
 * 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
        if(l1 == nullptr && l2 == nullptr) {
            return nullptr;
        }
        if (l1 == nullptr) {
            return l2;
        }
        if (l2 == nullptr) {
            return l1;
        }
        
        ListNode *p = new ListNode();
        ListNode *head = p;
        if (l1->val < l2->val) {
            p->val = l1->val;
            l1 = l1->next;
        }
        else {
            p->val = l2 ->val;
            l2 = l2->next;
        }
        
        while (l1 != nullptr && l2 != nullptr) {
            if (l1->val <= l2->val) {
                ListNode *q = new ListNode (l1->val);
                p->next = q;
                p = p->next;
                l1 = l1->next;
            }
             else {
                ListNode *q = new ListNode (l2->val);
                p->next = q;
                p = p->next;
                l2 = l2->next;
            }
        }
        if (l1 != nullptr) {
            p->next = l1;
        }
        
        else if (l2 !=nullptr) {
            p->next = l2;
        }
     
        return head;
    }
};


LintCode 合并两个排序链表

标签:

原文地址:http://blog.csdn.net/susser43/article/details/46584827

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!