题目
应用中有时需要验证来自不同地方的两个表的信息是否一致。本实验编写具有如下功能的程序:输入两个学生记录表LIST1,LIST2,在表LIST2中找出所有没有在表LIST1中出现的学生记录(设表LIST1为基础数据表,非空)。
每一个学生记录元素包含两个数据项:学号(整数),姓名;
如果学生记录表LIST2中的记录都包含在LIST1中,则输出the records of LIST2 are all in the LIST1.
如果学生记录表LIST2中的存在学号,姓名不能与表LIST1完全匹配的记录,则输出 学号(%8d)姓名(%15s)is not in LIST1.
如果LIST2为空表,则输出the LIST2 is NULL.
思路
创建两个链表LIST1和LIST2, 在LIST1中查找LIST2即可.
注意要用strcmp函数进行比较.
创建链表函数写完后, 可以不着急完成main函数部分, 先调试确保已经写出来的部分正确.
代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
typedef struct Node//创建节点
{
int num;
char name[20];
struct Node* next;
} node;
node* head;
int daan = 0;
node* build(int mm)//创建链表
{
head = new node;
node *now = head;
memset (now->name,0,sizeof(now->name));
for(int j = 0; j < mm ;j++)
{
node *pp = new node;
int number = 0;
scanf("%d", &number );
pp->num = number;//存学号
char ch = getchar();
for(int t = 0; ; t++)
{
ch = getchar();
if( ch != '\n')
pp->name[t] = ch;//存名字
else break;
}
pp->next = NULL;
now->next = pp;
now = pp;
}
return head;
}
int main()
{
int m = 0, n = 0;
cin >> m;
node* biao1 = build(m);
cin >> n;
if(n == 0)//表2为空
{
printf("the LIST2 is NULL.\n");
return 0;
}
node* biao2 = build(n);
node *biao22 = biao2;
biao22 = biao22->next;
node *biao11 = biao1;
biao11 = biao11->next;
while(n--)
{
int k = 0;
for(k = 0; k < m; k++)
{
int c = strcmp(biao11->name,biao22->name);//要用strcmp函数!!
if(c==0 && biao11->num == biao22->num)
break;
else biao11 = biao11->next;
}
if(k == m) //没找到
{
printf("%8d %s is not in LIST1.\n",biao22->num,biao22->name);
daan++;
}
biao22 = biao22->next;
biao11 = biao1->next;//重置
}
if(daan==0)
printf("the records of LIST2 are all in the LIST1.\n");
return 0;
}