题目:输入两个递增排序的链表,合并这两个链表并使新链表的结点仍然是按照递增排序的。
程序源码如下:
#include <iostream>
struct ListNode
{
public:
ListNode()
{
data = 0;
}
int data;
ListNode *next;
};
void PrintList(const ListNode* pListHead)
{
while (pListHead)
{
std::cout << pListHead->data << " ";
pListHead = pListHead->next;
}
std::cout << std::endl;
}
void CreateList(ListNode*&pListHead, int *arr, int len)
{
pListHead = new ListNode();
pListHead->next = NULL;
ListNode *pNextNode, *pTmpNode;
pNextNode = pListHead;
if (arr && len >= 0)
{
for (int i = 0; i < len; i++)
{
pTmpNode = new ListNode();
pTmpNode->data = arr[i];
pNextNode->next = pTmpNode;
pNextNode = pNextNode->next;
}
pNextNode->next = NULL;
}
pListHead = pListHead->next;
}
ListNode* MergeList(ListNode *pListHead1, ListNode *pListHead2)
{
if (pListHead1 == NULL)
{
return pListHead2;
}
if (pListHead2 == NULL)
{
return pListHead1;
}
ListNode* pMergeHead = NULL;
if (pListHead1->data < pListHead2->data)
{
pMergeHead = pListHead1;
pMergeHead->next = MergeList(pListHead1->next, pListHead2);
}
else
{
pMergeHead = pListHead2;
pMergeHead->next = MergeList(pListHead1, pListHead2->next);
}
return pMergeHead;
}
int main()
{
ListNode *pListHead1 = new ListNode();
ListNode *pListHead2 = new ListNode();
int arr1[] = { 1, 3, 5, 7, 9 };
int arr2[] = {2, 4, 6, 8, 10};
CreateList(pListHead1, arr1, 1);
CreateList(pListHead2, arr2, 3);
PrintList(pListHead1);
PrintList(pListHead2);
pListHead1 = MergeList(pListHead1, pListHead2);
PrintList(pListHead1);
system("pause");
return 0;
}