两个有序链表序列的交集

题目描述

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

输入描述

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

输出描述

在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例

1 2 5 -1
2 4 5 8 10 -1

输出样例

2 5

提示

 链表

#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 *jiaoJi_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=jiaoJi_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
");
	    else{
	for(p=list;p->next!=NULL;p=p->next)
	{
		printf("%d ",p->mode);
	}
	printf("%d
",p->mode);}
}

struct node *jiaoJi_list(struct node *list1,struct node *list2){
	struct node *p,*q,*list3=NULL;
	for(p=list1;p!=NULL;p=p->next)
	{
		for(q=list2;q!=NULL;q=q->next)
		{
			if(p->mode==q->mode)
			    list3=add_list(list3,p->mode);
		}
	}
	return list3;	
}
原文地址:https://www.cnblogs.com/Romantic-Chopin/p/12451406.html