您的位置:首页 > 理论基础 > 数据结构算法

[leetcode 24] Merge Two Sorted Lists

2014-08-06 15:26 399 查看

题目:

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.同时遍历,一一比较即可

代码:

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