请大家帮个忙, 是关于C++方面的问题

zcl198715 2008-03-15 02:08:09
本程序是为了建一个链表!
并完成相关操作
#include<iostream>
#include<string>
using namespace std;
struct student
{
string name;
student *next;
};
void creat(student *first)//建立链表,并输入数据
{
student *current;
int a;
first=current=new student;
cout<<"输入姓名:\n";
cin>>current->name;
cout<<"继续输入(yes==1,no==0)"<<'\n';
cin>>a;
while(a)
{
current=current->next=new student;
cin>>current->name;
cout<<"继续输入(yes==1,no==0)"<<'\n';
cin>>a;
}
current->next=0;
cout<<"输入完成!\n";
}
void print(student *first)//输出
{
student *current;
current=first;
while(current!=0)
{
cout<<current->name<<'\n';
current=current->next;
}
}
void destroy(student *first)//销毁
{
student *current;
while(first!=0)
{
current=first->next;
delete first;
first=current;
}
cout<<"删除成功\n";

}
int main()
{
student *first=NULL;//为什么要将first赋值为NULL,可不可以不赋值啊?
creat(first);
print(first);//通过测试,我发现first为空,为什么?也就是说,first=0,但我定义的first是指针啊!
destroy(first);
return 0;
}

希望大家能给些帮助,不胜感谢!

...全文
117 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
avinchen 2008-03-15
  • 打赏
  • 举报
回复
也可以这样改一下
void creat(student *first)//建立链表,并输入数据
{
student *current;
int a;
current=first;
cout <<"输入姓名:\n";
cin>> current-> name;
cout <<"继续输入(yes==1,no==0)" <<'\n';
cin>> a;
while(a)
{
current=current-> next=new student;
cin>> current-> name;
cout <<"继续输入(yes==1,no==0)" <<'\n';
cin>> a;
}
current-> next=0;
cout <<"输入完成!\n";
}

int main()
{
student *first=new student();//为什么要将first赋值为NULL,可不可以不赋值啊?
creat(first);
print(first);//通过测试,我发现first为空,为什么?也就是说,first=0,但我定义的first是指针啊!
destroy(first);
return 0;
}

danny1221 2008-03-15
  • 打赏
  • 举报
回复
用指针引用吧,
void creat(student*& first)
void destroy(student*& first)
因为是引用,所以在creat和destory里的first只是main里first的别名,在这些函数里对first的任何改变,都是直接对main里first的改变.
TeddyGe 2008-03-15
  • 打赏
  • 举报
回复
是输出参数的问题, 你这样New了带不出值来的.

可以像LS 说的那样, 用二级指针, 也可以选择用引用的方式.

ttkk_2007 2008-03-15
  • 打赏
  • 举报
回复

1.void creat(student **first)//建立链表,并输入数据 ,需要二级指针
2.creat(first); //create(&first);
zcl198715 2008-03-15
  • 打赏
  • 举报
回复
听大家建议,我用了二维指针!
student **first=NULL;
那**first表示什么? *first又表示什么?
可不可以把用二维指针表示的程序写在下面啊!
不胜感谢!
zcl198715 2008-03-15
  • 打赏
  • 举报
回复
谢谢各位啦!
我不知道该把那分给谁?
因为大家都说得太好了!
Inhibitory 2008-03-15
  • 打赏
  • 举报
回复
int main()
{
student *first=NULL;//为什么要将first赋值为NULL,可不可以不赋值啊?
// first 赋值为NULL是一种定义指针的习惯,是为了不小心使用了没有初始化的指针,
// 这种错误编译器是检查不出来的, 如果为NULL,调用它指向的对象时,编译器就能检查出来,是为了安全而这样做,
// 你也可以不赋值为NULL,这不过是一种良好的使用指针的习惯罢了.
creat(first); // 因为不是二级指针,所以first的值不会变,变的是他所指向的内存区域的值,但first这里是NULL,显然不行
// 要理解指针的值与指针所指向的内存区域不是同一个概念
// 要改变一个变量的值,可以把它的地址传给一个函数来改变, 所以,你想要改变first的值,就得传first的地址,而不是first本身
// 这里你传的是first自己,而不是他的地址,所以first仍然是0
print(first);//通过测试,我发现first为空,为什么?也就是说,first=0,但我定义的first是指针啊!
destroy(first);
return 0;
}

64,662

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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