两个有序链表合并成一个有序链表

//两个增序链表的合并,有序链表带空白头结点 
#include<iostream>
using namespace std;

struct node{
	int data;
	node * next; 
}; //这个分号不能少 

node * createList(){
	node * head, * rear;
	head=new node;//或者head=(node)malloc(sizeof(struct node)); 新建空白节点 
	rear=head;
	
	int data;cin>>data;
	while(data != -1){
		node * tmp=new node;
		tmp->data=data;
		rear->next=tmp;
		rear=tmp;
		cin>>data;
	}
	rear->next=NULL;
	return head;
}

node * mergeList(node * a,node *b){
	node *ha,* hb,* hc_head,* hc_rear;
	ha=a->next; 
	hb=b->next;
	hc_head=new node;
	hc_rear=hc_head;
	while(ha && hb){
		node * tmp=new node;
		if(ha->data <= hb->data){
			tmp->data=ha->data;
			hc_rear->next=tmp;
			hc_rear=tmp;
			ha=ha->next;			
		}else{
			tmp->data=hb->data;
			hc_rear->next=tmp;
			hc_rear=tmp;	
			hb=hb->next;		
		}				
	}
	
	while(ha){
		node *tmp=new node;
		tmp->data=ha->data;
		hc_rear->next=tmp;
		hc_rear=tmp;
		ha=ha->next;
	}	
	
	while(hb){
		node *tmp=new node;
		tmp->data=hb->data;
		hc_rear->next=tmp;
		hc_rear=tmp;
		hb=hb->next;
	}
	
	hc_rear=NULL;
	return hc_head;		
}

void * coutList(node * l){
	l=l->next;
	int flag=0;
	while(l){
		if(flag==0) flag=1;
		else cout<<" ";
	
	    cout<<l->data;
		l=l->next;	
	}
} 

int main(){
	node * a,* b,* c;
	a=createList();
	b=createList();
	c=mergeList(a,b);
	coutList(c); cout<<endl;
	return 0;
}

/*输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值