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

//将两个升序链合成为一条,即同时跑两根链表,遇到小值,指针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; 
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值