已知两个非降序链表序列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>
#include<malloc.h>
typedef struct Node *Node;
struct Node
{
int data;
Node Next;
};
int j=0;
void output(Node L);
void compel(Node L1,Node L2);
int main()
{
int i,n;
Node S[2];
for(i=0;i<2;i++)
{
S[i]=(Node)malloc(sizeof(struct Node));
S[i]->Next=NULL;
Node j=S[i];
while(scanf("%d",&n)!=EOF&&n>=0)
{
Node k=(Node)malloc(sizeof(struct Node));
k->data=n;
k->Next=NULL;
j->Next=k;
j=k;
}
}
compel(S[0],S[1]);
}
void compel(Node L1,Node L2)
{
int flag=1;
Node p;
p=L1->Next;
Node S=(Node)malloc(sizeof(struct Node));
S->Next=NULL;
while(p)
{
Node q=L2->Next;
while(q)
{
if(p->data==q->data)
{
Node t=(Node)malloc(sizeof(struct Node));
t->data=p->data;
t->Next=NULL;
S->Next=t;
S=t;
// if(flag)
// {
// flag=0;
// printf("%d",S->data);
// }
// else
// printf(" %d",S->data);
}
q=q->Next;
}
p=p->Next;
}
output(S);
}
void output(Node L)//出问题的代码,结果是无法正常输出
{
int flag=1;
Node list=L->Next;
while(list)
{
if(flag)
{
flag=0;
printf("%d",list->data);
}
printf("*%d",list->data);
}
if(flag)
printf("NULL");
}
请各位大大指点一下,感激不尽。