码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode(8):merge two sorted list

时间:2015-06-18 09:36:19      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1)
    return l2;
    if(!l2)
    return l1;
    ListNode* head=NULL;
    head=((l1->val) < (l2->val))?  l1:l2;
    ListNode* p2=NULL;
    p2=((l1->val) >= (l2->val))?  l1:l2;
    
    ListNode* p1=head;
    
    while(p1->next && p2)
    {
    if((p1->next->val) <= (p2->val))
    p1=p1->next;
    else
    {
    ListNode* tmp1=p1->next;
    ListNode* tmp2=p2->next;
    p1->next=p2;
    p2->next=tmp1;
    p1=p2;
    p2=tmp2;
    }
    }
    
    if(!(p1->next))
    p1->next=p2;
    return head;
    }
};


leetCode(8):merge two sorted list

标签:

原文地址:http://blog.csdn.net/walker19900515/article/details/46543771

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