一个没有C币的萌新,想问问大佬们一些关于程序停止运行的小问题

974720161 2018-04-28 08:39:29
下面是我敲的一段代码,但是总是在进行插入和显示所有这两项功能时,程序停止运行,我想问下这是为什么啊?
#include<iostream.h>
#include<string>
typedef struct student
{
int id;
float score;
char name[10];
student *next;
}stu;

stu *head=NULL;

void record();
void insert();
void delt();
void locate();
void print();



int main()
{
int c,i=1;
cout<<"1、输入学生成绩 2、插入 3、删除 4、查找 5、显示所有 0、退出"<<endl;
cin>>c;
do
{
switch(c)
{
case 0: i=0; break;
case 1: record(); break;
case 2: insert(); break;
case 3: delt(); break;
case 4: locate(); break;
case 5: print(); break;
default: cout<<"输入有误!"<<endl; break;
}
cout<<"输入选择(0-7): ";
cin>>c;
}while(c!=0);
return 0;
}


void record()
{
stu *p,*q;
int i,n;
cout<<"输入学生人数:";
cin>>n;
i=0;
cout<<"输入学生信息:姓名 学号 成绩"<<endl;
while(i<n)
{
p=new stu;
if(head==NULL)
{
head=p;
q=head;
}
else
{
cin>>p->name>>p->id>>p->score;
q->next=p;
q=p;
i++;
}
}
}

void insert()
{
stu *p=head, *s=NULL,*q=NULL;
int x,count=0;
cout<<"插入的位置为:";
cin>>x;
p=q->next;
while(p!=NULL && count<x-1)
{
q=p;
p=q->next;
count++;
}
if(p=NULL) cout<<"位置错误";
else
{
cout<<"请输入插入学生的信息:姓名 学号 成绩"<<endl;
s=new stu;
cin>>p->name>>p->id>>p->score;
s->next=p->next;
p->next=s;
}
}

void delt()
{
stu *p,*q;
int id,i=1;
cout<<"输入要删除学生的学号: ";
cin>>id;
q=head;
p=q->next;
while(i)
{
if(p->id==id)
{
q->next=p->next;
delete p;
i=0;
break;
}
q=p;
p=q->next;
}
}

void locate()
{stu *p,*q;
int id,i=1;
cout<<"输入要查找学生的学号: ";
cin>>id;
q=head;
p=q->next;
while(i)
{
if(p->id==id)
{
cout<<p->name<<","<<p->score<<endl;
i=0;
}
q=p;
p=q->next;
}
}

void print()
{
stu *p;
p=head->next;
while(p)
{
cout<<p->name<<","<<p->score<<endl;
p=p->next;
}
}
...全文
923 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2018-05-03
  • 打赏
  • 举报
回复
数据结构对单链表进行数据排序 http://bbs.csdn.net/topics/392201633
974720161 2018-05-02
  • 打赏
  • 举报
回复
insert函数改为这样 void insert() { stu *p=head, *s=NULL; p=new stu; int x,count=0; cout<<"插入的位置为:"; cin>>x; while(p!=NULL && count<x-1) { p=p->next; count++; } if(p==NULL) cout<<"位置错误"; else { cout<<"请输入插入学生的信息:姓名 学号 成绩"<<endl; s=new stu; cin>>p->name>>p->id>>p->score; s->next=p->next; p->next=s; } } print函数改为了这样void print() { if(head==NULL) return; stu *p; p=head->next; while(p) { cout<<p->name<<","<<p->score<<endl; p=p->next; } } 但还是无法解决
Isnis-fallen 2018-04-29
  • 打赏
  • 举报
回复
print函数里要保证head不为NULL if(head==NULL) return;
paschen 2018-04-28
  • 打赏
  • 举报
回复
此外,insert函数中,q是NULL,但你p = q->next; 直接解引NULL指针
paschen 2018-04-28
  • 打赏
  • 举报
回复
if (p = NULL) 改成; if (p == NULL)

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧