题目描述
有序合并两个链表主要注意三点:
1、同步遍历;
2、结点值大小判断;
3、同步遍历结束之后,还要记住判断是否还存在某个链表没有遍历完全;
细节见代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL)
{
return pHead2;
}
else if (pHead2 == NULL)
{
return pHead1;
}
ListNode *newHead = new ListNode(0);
ListNode *tail = newHead;
ListNode *temp1 = pHead1;
ListNode *temp2 = pHead2;
while (temp1 != NULL && temp2 != NULL)
{
if (temp1->val <= temp2->val)
{
ListNode *temp = new ListNode(temp1->val);
temp->next = tail->next;
tail->next = temp;
tail = temp;
temp1 = temp1->next;
}
else
{
ListNode *temp = new ListNode(temp2->val);
temp->next = tail->next;
tail->next = temp;
tail = temp;
temp2 = temp2->next;
}
}
if (temp1 != NULL)
{
tail->next = temp1;
}
if (temp2 != NULL)
{
tail->next = temp2;
}
return newHead->next;
}
};