您的位置:首页 > 其它

【leetcode】Merge Two Sorted Lists

2015-01-26 23:25 274 查看

Merge Two Sorted Lists

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.

每次找到两个链表中小的一个,把他连接在后面,直到连接完成

思路1:利用递归方法解:递归思路:

if(l1->val<=l2->val)

{
head=l1;
head->next=mergeTwoLists(l1->next,l2);
}
else
{
head=l2;
head->next=mergeTwoLists(l1,l2->next);
}

class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {

if(l1==NULL)
{
return l2;
}

if(l2==NULL)
{
return l1;
}

ListNode *head;

if(l1->val<=l2->val)
{
head=l1;
head->next=mergeTwoLists(l1->next,l2);
}
else
{
head=l2;
head->next=mergeTwoLists(l1,l2->next);
}

return head;

}
};


非递归解法:

/**
* 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 *head=new ListNode(0);
ListNode *pre=head;

while(l1!=NULL||l2!=NULL)
{
if(l1==NULL)
{
head->next=l2;
l2=l2->next;
head=head->next;
continue;
}

if(l2==NULL)
{
head->next=l1;
l1=l1->next;
head=head->next;
continue;
}

if(l1->val<=l2->val)
{
head->next=l1;
l1=l1->next;
head=head->next;
}
else
{
head->next=l2;
l2=l2->next;
head=head->next;
}
}

ListNode *ret=pre->next;
delete pre;
return pre->next;

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