您的位置:首页 > 其它

LeetCode 21 Merge Two Sorted Lists

2015-04-27 14:45 441 查看

题目



分析

归并的时候一定要注意一边已经被归并完了的情况。

题解

class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL && l2==NULL)
return NULL;
struct ListNode head(0);
struct ListNode *p = &head;
struct ListNode *q = p;
while(l1!=NULL || l2!=NULL)
{
struct ListNode *temp = new struct ListNode(0);
if(l1==NULL)
{
temp->val=l2->val;
l2=l2->next;
q->next=temp;
q=q->next;
}
else if(l2==NULL)
{
temp->val=l1->val;
l1=l1->next;
q->next=temp;
q=q->next;
}
else
{
if(l1->val < l2->val)
{
temp->val=l1->val;
l1=l1->next;
q->next=temp;
q=q->next;
}
else
{
temp->val=l2->val;
l2=l2->next;
q->next=temp;
q=q->next;
}
}
}
p=p->next;
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: