输入描述:
输入有四行:
第一行:LA的长度m
第二行:m个整数,用空格隔开
第三行:LB的长度n
第四行:n个整数,用空格隔开
输出描述:
输出链表LA
样例输入:
3 1 2 3 3 4 1 3
样例输出:
The List is: 3 1
方法:
遍历LB中的结点元素,如果有与LA相同的就存入到LC中。
#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>
using namespace std;
#define ERROR 0
typedef struct LNode {
int data; //结点的数据域
struct LNode *next; //结点的指针域
} LNode, *List; //LinkList为指向结构体LNode的指针类型
void InitList(List &L); //创建链表(带头结点)
void ListInput(List &L, int n); //链表数据的输入
void ListOutput(List L); //输出List
//void ListInsert(List &L, int i,int e); //将e插入到List中第i个元素的位置
//void ListDelete(List &L, int i); //将删除List中第i个元素
bool LocateElem(List L, int e); //判断List里有没有e这个元素
void ListInsert(List &L, int e); //将e插入到List中
void IntersecList(List LA, List LB,List &LC); //线性表的交集(链表)
int main()
{
int m,n;//定义链表中输入元素的个数,LA有m个元素,LB有n个元素
int i,e;
List LA,LB,LC;
InitList(LA);//初始化LA
cin>>m;//输入LA的元素的个数
ListInput(LA, m);//输入LA的m个元素
InitList(LB);//初始化LB
cin>>n;//输入LB的元素的个数
ListInput(LB, n);//输入LB的n个元素
InitList(LC);//初始化LC
IntersecList(LA,LB,LC) ; // 求交
ListOutput(LC);
return 0;
}
void ListInput(List &L, int n) //链表数据的输入
{
int i=1;
List p, r;
r = L;
while (i<=n) {
p = new LNode;
cin >> p->data;
p->next = NULL;
r->next = p;
r = p;
i++;
}
}
void ListOutput(List L) //输出List
{
List p;
p = L->next;
cout << "The List is:"<<endl;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void InitList(List &L) //创建链表
{
L = new LNode;
L->next = NULL;
}
void ListInsert(List &L, int e) //将e插入到List中(前插)
{
List p;
p = new LNode;
p->data = e;
p->next = L->next;
L->next = p;
}
bool LocateElem(List L, int e) //判断List里有没有e这个元素
{
List p;
p = L->next;
while (p != NULL) {
if (p->data == e)
return true;
p = p->next;
}
return false;
}
void IntersecList(List LA, List LB,List &LC)
{
LB=LB->next;
while(LB!=NULL)
{
if(LocateElem(LA, LB->data))
{
ListInsert(LC, LB->data);
}
LB=LB->next;
}
}
/*或者
void IntersecList(List LA, List LB,List &LC)
{
List p;
p=LB->next;
while(p!=NULL)
{
if(LocateElem(LA, p->data))
{
ListInsert(LC, p->data);
}
p=p->next;
}
}
*/