已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
代码片
#include <stdio.h>
#define MAXSIZE 20
typedef struct Node *List;
struct Node {
int data;
List next; /* 保存线性表中最后一个元素的位置 */
};
List CreatList(List L);
int main()
{
List S1=NULL,S2=NULL,S3=NULL,a,b,c,p;
S1=CreatList(S1);
S2=CreatList(S2);
S3=(List)malloc(sizeof(struct Node));
S3->next=NULL;
a=S1;
b=S2;
c=S3;
for(;a!=NULL && b!=NULL;){
if(a->data==b->data){
c->next=a;
c=c->next;
a=a->next;
b=b->next;
}
else if(a->data>b->data)
b=b->next;
else a=a->next;
}
if(S3->next==NULL||S2==NULL||S1==NULL) printf("NULL");
else{
p=S3->next;
while(p!=NULL){
printf("%d",p->data);
if(p->next!=NULL) printf(" ");
p=p->next;
}
}
return 0;
}
List CreatList(List L){
int x;
List p,last;
scanf("%d",&x);
while(x>=0){
p=(List)malloc(sizeof(struct Node));
p->data=x;
if(L==NULL){
p->next=L;/*p指针指向头部*/
L=p;/*头指针指向P*/
last=p;/*last指针指向p*/
/*则插入p到链表头部*/
}
else{
last->next=p;/*上次循环p指针指向此p指针*/
p->next=NULL;
last=p;
}
scanf("%d",&x);
}
return L;
}
复习
一个多月后用C++写
#include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
vector<int> num1,num2,q;
int m;
while(1){
cin>>m;
if(m<0) break;
num1.push_back(m);
}
while(1){
cin>>m;
if(m<0) break;
num2.push_back(m);
}
int i=0,j=0;
while(i<num1.size()&&j<num2.size()){
if(num1[i]==num2[j]){
q.push_back(num1[i]);
i++;
j++;
}
else if(num1[i]>num2[j]) j++;
else if(num1[i]<num2[j]) i++;
}
if(q.size()<=0) cout<<"NULL";
else{
for(int i=0;i<q.size()-1;i++)
cout<<q[i]<<" ";
cout<<q[q.size()-1];
}
return 0;
}