一道实验题目,求助
4.编写程序:建立一个学生数据链表,每个结点信息包括如下内容:学号、姓名、性别、年龄和专业。对该链表作如下处理:(1)输入一个学号,如果链表中的结点中包含该学号,则将此结点删去(最多只有一个节点)。(2)输入一个专业,如果链表中的结点包含该专业,则将此结点删去(可能有多个节点)。
#include <iostream>
using namespace std;
#include <cstring>
const int N=3;
struct student
{
int number;
char name[20];
char sex[20];
int age;
char major[20];
struct student *next;
};
int main()
{
struct student stu[N] ,*p,*q;
int i,number,flag;
char major[20];
p=stu;
stu[0].number=1;
strcpy(stu[0].name,"Mrak");//这个地方值得注意,数组不能赋值
strcpy(stu[0].sex,"Female");
stu[0].age=19;
strcpy(stu[0].major,"CS");
stu[1].number=2;
strcpy(stu[1].name,"Steve");
strcpy(stu[1].sex,"Female");
stu[1].age=24;
strcpy(stu[1].major,"SE");
stu[2].number=3;
strcpy(stu[2].name,"Mao");
strcpy(stu[2].sex,"Female");
stu[2].age=20;
strcpy(stu[2].major,"CS");
stu[0].next=&stu[1];
stu[1].next=&stu[2];
stu[2].next=NULL;
do //首先输出原始数据
{
cout<<p->number<<","<<p->name<<","<<p->sex<<","<<p->age;
cout<<","<<p->major<<endl;
p=p->next;
}
while(p!=NULL);
cout<<endl;
cout<<"Please input a student's number"<<endl;
cin>>number;
cout<<"Please select a major from CS(Computer Science) and SE(Software Engineering)"<<endl;
cin.getline(major,20);
cin.get();//不是很理解为什么每一次用getline都必须加这个。。。
for(i=0; i<N; i++)
{
if((i!=N-1)&&(i!=0))//首先对首非末项进行处理
{
p=&stu[i];
q=&stu[i-1];
if((p->number==number)||strcmp(p->major,major)==0)
{
q->next=p->next;
delete p;
}
}
else if(i==0)
{
p=stu;
if((p->number==number)||strcmp(p->major,major)==0)
{
flag=0;//对首项进行标记处理
delete p;
}
}
else //对末项进行处理
{
p=&stu[i];
q=&stu[i-1];
if((p->number==number)||strcmp(p->major,major)==0)
{
q->next=NULL;
delete p;
}
}
}
if(flag==0) p=&stu[1];
else p=stu;
//输出经过筛选过后的数据
do
{
cout<<p->number<<","<<p->name<<","<<p->sex<<","<<p->age;
cout<<","<<p->major<<endl;
p=p->next;
}while(p!=NULL);
}