[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;
}
};
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;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- [C/C++]反转链表
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 用VBScript写合并文本文件的脚本
- C#实现基于链表的内存记事本实例
- oracle列合并的实现方法
- 使用BAT一句话命令实现快速合并JS、CSS
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- SQL 合并多行记录的方法总汇
- C#自适应合并文件的方法
- C++联合体转换成C#结构的实现方法
- C# Pointer指针应用实例简述
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析