码迷,mamicode.com
首页 > 其他好文 > 详细

将两个有序链表和为另外一个链表,并保证有序

时间:2014-07-30 20:57:14      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:有序链表合并

直接递归

代码:

#include <iostream>
#include <stack>
using namespace std;

 typedef struct listNode{
	int key;
	struct	listNode *pNext;
 } * pNode,Node;

void createNode(pNode &pHead){
		bool isFirst=true;
		int temp;
		scanf("%d",&temp);
		pNode p=pHead,q;
		while(temp!=0){
			q=(pNode)malloc(sizeof(Node));
			q->key=temp;
			q->pNext=NULL;
			if(isFirst){
				p=pHead=q;
				isFirst=false;
			}else{
				p->pNext=q;
				p=q;
			}

			scanf("%d",&temp);
		}
		cout<<"原链表是:"<<endl;
		p=pHead;
		while(p){
			cout<<p->key<<" ";
			p=p->pNext;
		}
}
void print(const pNode merge){
	pNode p=merge;
	while(p){
		cout<<p->key<<" ";
		p=p->pNext;
	}
}
pNode merge(const pNode pHead1,const pNode pHead2){
	
	if(pHead1==NULL)
		return pHead2;
	else if(pHead2==NULL)
		return pHead1;
	pNode pMerge=NULL;
	if(pHead1->key > pHead2->key){
		pMerge = pHead2;	
    	pMerge->pNext = merge(pHead1,pHead2->pNext);
	}else{
		pMerge=pHead1;	
		pMerge->pNext=merge(pHead1->pNext,pHead2);
	}
	
	return pMerge;
}
void printListReverse(const pNode pHead){
	if(pHead==NULL)
		return;
	printListReverse(pHead->pNext);
	cout<<pHead->key;

}

int main(){
	pNode pHead1=NULL;
	pNode pHead2=NULL;

	createNode(pHead1);
	createNode(pHead2);
	pNode merge1 = merge(pHead1,pHead2);
	print(merge1);
	return 0;

}

运行结果:

bubuko.com,布布扣

将两个有序链表和为另外一个链表,并保证有序,布布扣,bubuko.com

将两个有序链表和为另外一个链表,并保证有序

标签:有序链表合并

原文地址:http://blog.csdn.net/buyingfei8888/article/details/38304135

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!