- 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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
题目解析:二个链表按大小合并,没啥好说得啦,比较大小,放入新链表中,遍历即可。
代码:
/**
* 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 * merge = new ListNode(0);//新建链表
ListNode * cur = merge;//新建指针指向该链表
if(l1 == NULL)
{
return l2;
}
if(l2 == NULL)
{
return l1;
}
while(l1 != NULL && l2 != NULL)//都不为空,比较大小,将较小值放入新建链表,直至链表都为空
{
if(l1->val <= l2->val)
{
cur->next = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1 != NULL)//l2为空,直接将l1赋给新建链表
{
cur->next = l1;
}
if(l2 != NULL)//l1为空,直接将l2赋给新建链表
{
cur->next = l2;
}
return merge->next;
}
};
性能:
结束语:LeetCode中只识别NULL,不能识别null,请注意,欢迎大家留言交流,谢谢!