合并两个排序的链表

剑指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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值