为什么说我的代码在链表为空和大规模数据情况下不对
两个有序链表序列的交集
已知两个非降序链表序列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>
typedef struct LNode{
int data;
struct LNode *next;
}*List, LNode;
List merge(List S1, List S2); //用于求交集
List build(); //输入并建立链表
void Print(List S); //输出链表
int main(){
List S1, S2, S3;
S1 = build();
S2 = build();
S3 = merge(S1, S2);
Print(S3);
return 0;
}
List merge(List S1, List S2){
if(!S1 || !S2)
return NULL;
LNode *p = S1, *q = S2;
LNode *k;
List head = NULL;
while(p && q){
while(p->data > q->data){
q = q->next;
if(!q)
return head;
}
while(p->data < q->data){
p = p->next;
if(!p)
return head;
}
//q->data == p->data 情况下才会执行
LNode *newnode = (LNode*)malloc(sizeof(LNode));
newnode->data = p->data;
newnode->next = NULL;
if(!head){
head = newnode;
k = head;
}
else{
k->next = newnode;
k = k->next;
}
p = p->next;
q = q->next;
}
return head;
}
List build(){
List S = (List)malloc(sizeof(LNode));
int n;
scanf("%d", &n);
if(n == -1)
return NULL;
S->data = n;
S->next = NULL;
LNode *p = S;
while(scanf("%d", &n) == 1 && n != -1){
LNode *newnode = (List)malloc(sizeof(LNode));
newnode->data = n;
newnode->next = NULL;
p->next = newnode;
p = p->next;
}
return S;
}
void Print(List S){
if(!S){
printf("NULL");
return;
}
LNode *p = S;
int first = 1;
while(p){
if(first){
first = 0;
printf("%d", p->data);
}
else
printf(" %d", p->data);
p = p->next;
}
}
结果


