题目来源:LintCode
原题地址:http://www.lintcode.com/zh-cn/problem/merge-two-sorted-lists/
题目:
将两个排序链表合并为一个新的排序链表
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 1->3->8->11->15->null
,2->null
, 返回1->2->3->8->11->15->null
。
难度级别:
容易
容易
思路分析:
说实话,本题思路上没什么难度的,只要考虑清楚边界条件,已经空指针等特殊条件就可以了。
其他按照正常的指针操作就可以了。
说实话,本题思路上没什么难度的,只要考虑清楚边界条件,已经空指针等特殊条件就可以了。
其他按照正常的指针操作就可以了。
实现代码:
#include <iostream>
using namespace std;
//Definition of ListNode
class ListNode {
public:
int val;
ListNode *next;
ListNode(int val) {
this->val = val;
this->next = NULL;
}
};
void display(ListNode *p);
class Solution
{
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
{
return l2;
} else if (l2 == NULL)
{
return l1;
}
ListNode *p1 = l1;
ListNode *p2 = l2;
ListNode *pH = NULL;
ListNode *p = NULL;
while (p1 != NULL && p2 != NULL)
{
//cout << p1->val << endl;
if (p1->val > p2->val)
{
if (pH == NULL)
{
pH = p2;
p = pH;
p2 = p2->next;
} else
{
p->next = p2;
p = p->next;
p2 = p2->next;
}
} else
{
if (pH == NULL)
{
pH = p1;
p = pH;
p1 = p1->next;
} else
{
p->next = p1;
p = p->next;
p1 = p1->next;
}
}
//display(pH);
}
if (p1 != NULL)
{
p->next = p1;
}
if (p2 != NULL)
{
p->next = p2;
}
return pH;
}
};
void insertListNode(ListNode *p, int *pt, int N)
{
for (int i = 0; i < N; i++)
{
ListNode *tmp = new ListNode(pt[i]);
p->next = tmp;
p = p->next;
}
return;
}
void display(ListNode *p)
{
if (p == NULL)
return;
cout << p->val;
p = p->next;
while (p != NULL)
{
cout << "->" << p->val;
p = p->next;
}
cout << endl;
return;
}
int main()
{
int nums1[] = { 3, 8, 11, 15 };
int nums2[] = { 2, 4};
ListNode *p1 = new ListNode(1);
ListNode *p2 = new ListNode(2);
insertListNode(p1, nums1, 4);
<span><strong></strong></span><pre name="code" class="cpp"> insertListNode(p1, nums2, 1);
Solution st;ListNode *p = st.mergeTwoLists(p1, p2);display(p);return 0;}
代码说明:
这次的代码,我也同时附上了写测试用例的方法,只要在数组中更改就可以了.
这次的代码,我也同时附上了写测试用例的方法,只要在数组中更改就可以了.