已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL
。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
这里我用C模拟链表
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int data;
struct node* next;
};
int main(){
node* s1 = new node, *s2 = new node, *s3 = new node;
node* p, *q = s1;//s1是头节点
int data;
while(cin >> data && data != -1){
p = new node;
p->data = data, p->next = nullptr;
q->next = p;
q = p;
}
q = s2;
while(cin >> data && data != -1){
p = new node;
p->data = data, p->next = nullptr;
q->next = p;
q = p;
}
//新链表
p = s1 -> next, q = s2 -> next;
node* t, *pre = s3;
while(p != nullptr && q != nullptr){
if(p -> data == q -> data){
t = new node;
t->data = p->data, t->next = nullptr;
pre->next = t;
pre = t;
p = p->next, q = q->next;
}else if(p->data < q->data){
p = p->next;
}else{
q = q->next;
}
}
//打印新的链表s3
t = s3 -> next;
int cnt = 1;
while(t != nullptr){
if(cnt) cout << t->data, cnt = 0;
else cout << ' ' << t->data;
t = t -> next;
}
if(cnt) puts("NULL");//新链表为空
return 0;
}