您的位置:首页 > 编程语言 > C语言/C++

[C++]Merge Two Sorted Lists 归并两个排序的链表

2015-08-23 20:08 459 查看
leetcode 原题链接:https://leetcode.com/problems/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.

简要翻译:归并两个已排序的链表,并作为一个新链表返回。新链表应该是原链表拼接而成的。即要在原链表上进行拼接操作。

简要分析:此题不难,但是要考虑到链表的特性,即链表是否为空的特性,还需注意指针的操作。

实现代码:

class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;

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