已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include
#include
#define MaxSize 1000
using namespace std;
typedef struct {
int data[MaxSize];
int length;
}Sqlist;
void inlist(Sqlist& l)
{
l.length = 0;//初始化
l.data[1000]={1};
}
void creatlist(Sqlist& l)
{
int j;
for (int i = 0;; i++)
{
cin >> j;
if (j>=1)
{
l.data[i] = j;
l.length++;
}
if(j==-1)
break;
}
}
void inlist1(Sqlist& m)
{
m.length = 0;//初始化
m.data[1000]={};
}
void creatlist1(Sqlist& m)
{
int j;
for (int i = 0;; i++)
{
cin >> j;
if (j>=1)
{
m.data[i] = j;
m.length++;
}
if(j==-1)
break;
}
}
void get(Sqlist l, Sqlist m)
{
int data1[1000];
int a; a = 0;
for (int i = 0; i < l.length; i++)
{
for (int j = 0; j < m.length; j++)
{
if (l.data[i] == m.data[j])
{
data1[a] = l.data[i];
a++;
}
}
}
if (a == 0)
cout << "NULL";
else
{
for (int i = 0; i < a; i++)
{
if (i < a - 1)
cout << data1[i] << " ";
else if(i==a-1)
cout << data1[i];
}
}
}
int main()
{
Sqlist l;
Sqlist m;
inlist(l);
creatlist(l);
inlist1(m);
creatlist1(m);
get(l, m);
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
#include "stdio.h"
#include "math.h"
#define N 100000
typedef struct linknode
{
int data;
struct linknode *next;
}node,*ptr;
int main(){
ptr s1,s2,s3,p,q,z,last;
int x;
s1 = NULL;
s2=NULL;
s3=NULL;
/* 前向插入
while (x>=0) {
p=(ptr)malloc(sizeof(node));
p->data=x;
//前向插入足矣
p->next=head;
head=p;
scanf("%d",&x);
}*/
//后向插入方法
scanf("%d",&x);
while(x>=0){
p=(ptr)malloc(sizeof(node));
p->data=x;
if (s1==NULL) {
p->next=s1;s1=p;last=p;
}else{
last->next=p;p->next=NULL;last=p;
}
scanf("%d",&x);//read next
}
scanf("%d",&x);
while (x>=0) {
p=(ptr)malloc(sizeof(node));
p->data=x;
if (s2==NULL) {
p->next=s2;s2=p;last=p;
}else{
last->next=p;p->next=NULL;last=p;
}
scanf("%d",&x);
}
// p = s1;
// while (p!=NULL) {
// printf("%d",p->data);
// p=p->next;
// }
// p = s2;
// while (p!=NULL) {
// printf("%d",p->data);
// p=p->next;
// }
//
s3=(ptr)malloc(sizeof(node));
s3->next=NULL;
for (p=s1,q=s2,z=s3; p!=NULL && q!=NULL; ) {
if (p->data==q->data) {
z->next=p;
z=z->next;
//printf("%d",p->data);
p=p->next;
q=q->next;
}else if (p->data<q->data){
p=p->next;
}else if (p->data>q->data){
q=q->next;
}
}
if ((s3->next==NULL||s1==NULL)||s2==NULL) {
printf("NULL");
}else{
p = s3->next;
while (p!=NULL) {
printf("%d",p->data);
if (p->next!=NULL) {
printf(" ");
}
p=p->next;
}
}
// p = s1;
// while (p!=NULL) {
// printf("%d",p->data);
// p=p->next;
// }
}
感谢点赞 有帮助关注一波啊