合并两个有序链表

给出两个有序链表,合并成一个链表之后依然有序。

我想到的解题思路就是先让两个链表头结点去比较,找出较小的一个作为新链表的头结点,之后再去比较两个链表中剩下的结点,每次选中结点一个就让指向该节点的指针向后走一个,并且使指向新链表当前结点的指针也向后走一个,直到两个链表中至少有一个链表的当前指针指向空,就将剩下的另一个链表中所有节点链进新链表,最后返回头结点。

这里给了两种方法,分别是非递归和递归,代码如下:

Node* MergeList_Nor(Node* pHead1, Node* pHead2)  //合并单链表(非递归)
{
	if(pHead1 == NULL)
		return pHead2;
	if(pHead2 == NULL)
		return pHead1;

	Node* pHead = NULL;
	Node* p1 = pHead1;
	Node* p2 = pHead2;

	if(p1->_data < p2->_data)
	{
		pHead = p1;
		p1 = p1->_next;
	}
	else
	{
		pHead = p2;
		p2 = p2->_next;
	}

	Node* pCur = pHead;
	while(p1 && p2)
	{
		if(p1->_data < p2->_data)
		{
			pCur->_next = p1;
			p1 = p1->_next;
		}
		else
		{
			pCur->_next = p2;
			p2 = p2->_next;
		}
		pCur = pCur->_next;
	}
	if(p1)
	{
		pCur->_next = p1;
	}
	else
	{
		pCur->_next = p2;
	}
	return pHead;
}

Node* MergeList(Node* pHead1, Node* pHead2)   //合并单链表(递归)
{
	if(pHead1 == NULL)
		return pHead2;
	if(pHead2 == NULL)
		return pHead1;

	Node* pHead = NULL;
	if(pHead1->_data < pHead2->_data)
	{
		pHead = pHead1;
		pHead->_next = MergeList(pHead1->_next, pHead2);
	}
	else
	{
		pHead = pHead2;
		pHead->_next = MergeList(pHead1, pHead2->_next);
	}
	return pHead;
}

当然测试代码时可能需要打印链表,最后不要忘记释放内存哟。下面是测试代码,可供参考:

#include <iostream>
using namespace std;

struct Node
{
	int _data;
	Node* _next;
	Node(int data):_data(data){}
};


Node* CreateList_1()   //创建有序链表1
{
	Node* pHead = NULL;
	Node* n1 = new Node(2);
	Node* n2 = new Node(4);
	Node* n3 = new Node(5);
	Node* n4 = new Node(9);

	pHead = n1;
	n1->_next = n2;
	n2->_next = n3;
	n3->_next = n4;
	n4->_next = NULL;

	return pHead;
}
Node* CreateList_2()    //创建有序链表2
{
	Node* pHead = NULL;
	Node* n1 = new Node(1);
	Node* n2 = new Node(3);
	Node* n3 = new Node(6);
	Node* n4 = new Node(7);

	pHead = n1;
	n1->_next = n2;
	n2->_next = n3;
	n3->_next = n4;
	n4->_next = NULL;

	return pHead;
}

void PrintList(Node* pHead)   //正向打印链表
{
	if(pHead == NULL)
	{
		cout<<"链表为空,无法打印!!!"<<endl;
		return;
	}
	Node* pCur = pHead;
	while(pCur)
	{
		cout<<pCur->_data<<"->";
		pCur = pCur->_next;
	}
	cout<<"NULL"<<endl;
}

void DestroyList(Node* pHead)  //销毁单链表,释放空间
{
	while(pHead)
	{
		Node* temp = pHead;
		pHead = pHead->_next;
		delete temp;
	}
}


void FunTest()
{
	Node* pHead1 = CreateList_1();
	Node* pHead2 = CreateList_2();
	Node* pHead = NULL;
	cout<<"合并之前的链表"<<endl;
	PrintList(pHead1);
	PrintList(pHead2);

	//pHead = MergeList_Nor(pHead1, pHead2);
	pHead = MergeList(pHead1, pHead2);
	cout<<"合并之后的链表"<<endl;
	PrintList(pHead);

	DestroyList(pHead);
}


int main()
{
	FunTest();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值