题目描述
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.
完整测试程序:
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
};
ListNode* MergeTwoSortedLists(ListNode* l1, ListNode* l2)
{
ListNode* newhead = NULL;
ListNode* p = NULL;
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
if (l1->val < l2->val){ newhead = l1; p = l1; l1 = l1->next; }
else{ newhead = l2; p = l2; l2 = l2->next; }
while (l1 && l2)
{
if (l1->val < l2->val)
{
p ->next= l1;
l1 = l1->next;
}
else
{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
p->next = l1 ? l1 : l2;
return newhead;
}
ListNode* CreateListNode(int value)
{
ListNode* pNode = new ListNode();
pNode->val = value;
pNode->next = NULL;
return pNode;
}
void DestroyList(ListNode* pHead)
{
ListNode* pNode = pHead;
while (pNode != NULL)
{
pHead = pHead->next;
delete pNode;
pNode = pHead;
}
}
void ConnectListNodes(ListNode* pCurrent, ListNode* pNext)
{
if (pCurrent == NULL)
{
printf("Error to connect two nodes.\n");
exit(1);
}
pCurrent->next = pNext;
}
int main()
{
ListNode* pNode1 = CreateListNode(1);
ListNode* pNode2 = CreateListNode(2);
ListNode* pNode3 = CreateListNode(3);
ListNode* pNode4 = CreateListNode(4);
ListNode* pNode5 = CreateListNode(5);
ListNode* pNode6 = CreateListNode(3);
ListNode* pNode7 = CreateListNode(5);
ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode4);
ConnectListNodes(pNode4, pNode5);
ConnectListNodes(pNode6, pNode7);
ListNode* p1 = pNode1;
ListNode* p6 = pNode6;
cout << "链表l1: ";
while (p1)
{
cout << p1->val << " ";
p1 = p1->next;
}
cout << endl;
cout << "链表l2: ";
while (p6)
{
cout << p6->val << " ";
p6 = p6->next;
}
cout << endl;
ListNode* res = MergeTwoSortedLists(pNode1, pNode6);
cout << "合并后链表: ";
while (res)
{
cout << res->val << " ";
res = res->next;
}
cout << endl;
system("pause");
DestroyList(res);
return 0;
}