湖北民族学院 OJ HBMY 1163 两个有序链表序列的合并

By  袁壮苗  2017级  计算机科学与技术专业 

题目描述

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。

输入描述

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出描述

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例

1 3 5 -1
2 4 6 8 10 -1

输出样例

1 2 3 4 5 6 8 10

提示

链表


[提交]   [统计]   [提问]

#include <stdio.h>
#include <stdlib.h>
struct node{
	int mode;
	struct node *next;
}; 
struct node *add_list(struct node *list,int n);
struct node *build_list();
struct node *heBing_list(struct node *list1,struct node *list2);
void print_list(struct node *list);
void paiXu_list(struct node *list);

struct node *first=NULL,*second=NULL,*third;
int main()
{
	first=build_list();
	second=build_list();
	third=heBing_list(first,second);
	print_list(third);
}


struct node *build_list(){
	struct node *p=NULL;
	int n;
	while(1)
	{
	    scanf("%d",&n);
		if(n==-1) return p;
		p=add_list(p,n);
	}
}
struct node *add_list(struct node *list,int n){
	struct node *p;
	p=(struct node*)malloc(sizeof(struct node));
	if(p==NULL) return NULL;
    p->mode=n;
	p->next=list;
	return p;
}
void print_list(struct node *list){
	struct node *p;
	
	if(list==NULL)
	    printf("NULL\n");
	    else{
	for(p=list;p->next!=NULL;p=p->next)
	{
		printf("%d ",p->mode);
	}
	printf("%d\n",p->mode);}
}
void paiXu_list(struct node *list){
	struct node *p,*q;
	for(p=list;p!=NULL;p=p->next)
	{
		for(q=list;q!=NULL;q=q->next)
		{
			if(q->mode>p->mode)
			{
				int m=q->mode;
				q->mode=p->mode;
				p->mode=m;
			}
		}
	}
}
struct node *heBing_list(struct node *list1,struct node *list2){
	struct node *p,*q,*list3=NULL;
	for(p=list1;p!=NULL;p=p->next){
		list2=add_list(list2,p->mode);
	}
	paiXu_list(list2);
	return list2;
}

猜你喜欢

转载自blog.csdn.net/qq_40763929/article/details/82763762
今日推荐