剑指0ffer17
题目分析:先找出头结点中最小的值,作为新链表的头结点,然后下节点作为新的头结点,继续合并链表剩余的节点。
注意:1.两个链表都为空,输出空。一个空,则输出另一个。
#include<iostream>
using namespace std;
struct ListNode{
int data;
ListNode* pNext;
};
//创建链表
void CreatList(ListNode* &pHead,int data)
{
ListNode* pNewNode = new ListNode();//新建存放数据的节点
pNewNode->pNext = NULL;
pNewNode->data = data;
if(NULL == pHead)
{
pHead = pNewNode;
}
else
{
ListNode* pNode = pHead;//新建遍历节点
while(pNode->pNext != NULL)
pNode = pNode->pNext;
pNode->pNext = pNewNode;
}
}
void PrintList(ListNode* &pHead)
{
if(pHead == NULL)
cout << "链表为空!"<< endl;
else
{
ListNode* pNode = pHead;
while(pNode != NULL)
{
cout << pNode->data << " ";
pNode = pNode->pNext;
}
}
cout << endl;
}
ListNode* MergeList(ListNode* pHead1,ListNode* pHead2)
{
if(pHead1 == NULL)
return pHead2;
else if(pHead2 == NULL)
return pHead1;
ListNode* pHead3 =NULL;
if(pHead1->data < pHead2->data)
{
pHead3 = pHead1;
pHead3->pNext = MergeList(pHead1->pNext,pHead2);
}
else
{
pHead3 = pHead2;
pHead3->pNext = MergeList(pHead1,pHead2->pNext);
}
return pHead3;
}
int _tmain(int argc, _TCHAR* argv[])
{
int num = 0;
ListNode* pHead1 = NULL;
ListNode* pHead2 = NULL;
cout << "请输入链表1:" << endl;
while(cin >> num)
{
if(num == -1)
break;
CreatList(pHead1,num);
}
cout << "输出链表1:" << endl;
PrintList(pHead1);
cout << "请输入链表2:" << endl;
while(cin >> num)
{
CreatList(pHead2,num);
}
cout << "输出链表2:" << endl;
PrintList(pHead2);
cout << "合并后的链表:" << endl;
ListNode* pMergedHead = MergeList(pHead1, pHead2);
PrintList(pMergedHead);
system("pause");
return 0;
}