将两个有序链表融合成一个有序链表

已知两个有序链表,将两个有序链表融合成一个有序链表的实现方法:

#include 
using namespace std;

typedef struct _listNode
{
	int data;
	struct _listNode *next;
}listNode;

void printList(listNode *plist)
{
	if(plist == NULL)
		return;

	listNode *tlist = plist;

	while(tlist != NULL)
	{
		cout << tlist->data << "\t";
		tlist = tlist->next;
	}
	cout << endl;
}

listNode *listNodeMerge(listNode *p1ist1, listNode *p1ist2)
{
	listNode *p1 = p1ist1;
	listNode *p2 = p1ist2;
	listNode *pcurr = NULL;
	listNode *pHead = NULL;
	listNode *pt = NULL;

	//先判断链表是否为空
	if(p1 == NULL && p2 != NULL)
		return p2;
	else if(p1 != NULL && p2 == NULL)
		return p1;
	else if(p1 == NULL && p2 == NULL)
		return NULL;

	//首先选择一个头节点
	if(p1->data < p2->data)
	{
		pHead = p1;
		p1 = p1->next;
	}
	else
	{
		pHead = p2;
		p2 = p2->next;
	}

	pcurr = pHead; //辅助指针

	while(p1 != NULL && p2 != NULL)
	{
		if(p1->data < p2->data)
		{
			pt = p1;
			p1 = p1->next;
		}
		else
		{
			pt = p2;
			p2 = p2->next;
		}

		pcurr->next = pt;
		pcurr = pcurr->next;
	}

	if(p1 != NULL) //其中有一个链表已经指向NULL,而另一个还没有指向NULL
		pcurr->next = p1;
	else
		pcurr->next = p2;

	return pHead;
}

int main()
{
	//为方便先定义两个有序链表,也可用new(malloc)的方式生成链表
	listNode n1,n3,n5;
	listNode n2,n4,n6,n7;

	n1.data = 1, n1.next = &n3;
	n3.data = 2, n3.next = &n5;
	n5.data = 3, n5.next = NULL;

	n2.data = 0, n2.next = &n4;
	n4.data = 4, n4.next = &n6;
	n6.data = 6, n6.next = &n7;
	n7.data = 9, n7.next = NULL;

	listNode *p1 = &n1;
	listNode *p2 = &n2;

	//打印该链表
	cout << "list1:\n";
	printList(p1);
	cout << "list2:\n";
	printList(p2);

	//打印融合后的链表
	cout << "After merge list:\n";
	listNode *pnew = listNodeMerge(p1, p2);

	printList(pnew);

	return 0;
}


你可能感兴趣的:(C程序学习日记,C++程序学习)