您的位置:首页 > 其它

[Leetcode] Merge two sorted lists 合并两已排序的链表

2017-06-14 09:18 597 查看

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->3->5->6和2->4->7->8,先将1放入新链表,然后将3和2比较,较小值放入新链表中,从1到3只要pre=pre->next即可。当其中有一条链表被访问完,结束循环,找出该链表,将其接在新链表的后面即可。

/**
* 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)
{
ListNode *newList=new ListNode(-1);
ListNode *pre=newList;
while(l1&&l2)
{
if(l1->val > l2->val)
{
pre->next=l2;
l2=l2->next;
}
else
{
pre->next=l1;
l1=l1->next;
}
pre=pre->next;
}
if(l1)
pre->next=l1;
else
pre->next=l2;

return newList->next;
}
};

 

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