您的位置:首页 > 其它

leetcode--Merge Two Sorted Lists

2017-05-02 21:18 483 查看
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.

思路:比较节点大小,如果l1大于l2,则继续寻找l2的下一节点直至找到该节点大于l1,然后开始l1中大于l2的节点。

/**
* 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==NULL) return l2;
if(l2==NULL) return l1;

ListNode* l3=l2->val<l1->val?l2:l1;
do{
ListNode *tmp;
if(l2->val<l1->val)
{
do{
tmp=l2;
l2=l2->next;
}while(l2&&l2->val<l1->val);
tmp->next=l1;

}
else
{
do{
tmp=l1;
l1=l1->next;
}while(l1&&l1->val<=l2->val);
tmp->next=l2;

}

}while(l1&&l2);
return l3;
}
};z
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: