您的位置:首页 > 编程语言 > Go语言

LeetCode Algorithms #21 <Merge Two Sorted Lists>

2016-02-24 18:38 531 查看
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.

思路:

就和玩积木一样,这些基本的链表操作是没有任何难度的,小心些,不犯低级错误就可以一次ac。

解:

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

ListNode* newListHead = nullptr;
ListNode* newListTail = nullptr;

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

while(true)
{
if(!l1)
{
newListTail->next = l2;
break;
}

if(!l2)
{
newListTail->next = l1;
break;
}

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

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