将两条升序链表合成一条升序链

//将两个升序链合成为一条,即同时跑两根链表,遇到小值,指针p指上去,然后处理当前结点,尾插到新的链表中

#include<stdio.h>
#include<stdlib.h>
#define N 5
typedef struct node{
	int data;
	struct node *next;
}ElemSN;
ElemSN *Creatlink(int a[])
{
	ElemSN *h,*tail;
	//创建头结点 
	h=tail=(ElemSN *)malloc(sizeof(ElemSN));
	 h->data=a[0];
	 h->next=NULL;
	 for(int i=1;i<N;i++){
	 	tail=tail->next=(ElemSN *)malloc(sizeof(ElemSN));
	 	tail->data=a[i];
		tail->next=NULL;
	 }
	 return h;
}
ElemSN *Fun(ElemSN *head1,ElemSN *head2)
{
	ElemSN *p,*h,*t;
	h=NULL;//新头 
	while(head1&&head2){
		if(head1->data<head2->data){//找出两条链中目前含有最小元素的结点 
			p=head1;
			head1=head1->next;
		}
		else{
			p=head2;
			head2=head2->next;
		}
	p->next=NULL;//拆出要尾插的元素,并给指针域赋空 
	//第一个结点,单独处理
	if(!h){
		h=t=p;
	} 
	else{//挂链  尾指针后移 
		t=t->next=p;
	}
}
	if(head1){//head1没完 
		p=head1;
	}
	else{//head2没完 
		p=head2;
	}
	t->next=p;//接上剩余元素 
	return h;
} 
void Printlink(ElemSN *h)
{
	ElemSN *p;
	for(p=h;p;p=p->next){
		printf("%4d",p->data);
	}
} 
int main()
{
	int a[N]={3,6,9,10,20};
	int b[N]={1,2,5,8,9};
	ElemSN *head1=NULL,*head2=NULL,*head=NULL;
	//正向创建单向链表
	head1=Creatlink(a);
	head2=Creatlink(b);
	head=Fun(head1,head2);
	//输出单向链表
	Printlink(head);
	return 0; 
} 

猜你喜欢

转载自blog.csdn.net/qq_42727102/article/details/88857806