首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求解链表有关问题!

2012-04-11 
求解链表问题!!#includeiostream#includestring#includefstream#includesstream#includeiomanip

求解链表问题!!
#include"iostream"
#include<string>
#include<fstream>
#include<sstream>
#include<iomanip>
using namespace std;

class student{
public:int id;
string name;
student *next;

student(int nid=0,string nname="noname");
} ;
student::student(int nid,string nname){id=nid;name=nname;}

class stunode{
student *head;
public:
stunode();
void linsert();
bool ldelete(int nid);
void show();
void doview();
};
stunode::stunode(){head=NULL;}

void stunode::linsert()
{student *p=new student();
cout<<"请输入学号:";
cin>>p->id;
cout<<"请输入姓名:";
cin>>p->name;

if(!head)
{head=p;}
else {
p->next=head;
head=p;
}

}
void stunode::show()
{student *p=head;
cout<<setw(10)/*设置输出宽度*/<<"学号"<<setw(8)<<"姓名"<<endl;

while(p){
cout<<setw(10)<<p->id<<setw(8)<<p->name<<endl;
p=p->next;
}
doview();
}
void stunode::doview()
{while(1){cout<<"1inter"<<"!!"<<"2show"<<"!!"<<"0exit"<<endl;
char n;
cin>>n;
switch(n)
{
case '1':
linsert();break;
case '2':
show();break;

}
}
}

main()
{stunode s;
s.doview();
}


当选择2 显示结果的时候,显示完后会出现错误,,初学 ,不会调试,求大师指点!!


[解决办法]
内存泄露伤不起

C/C++ code
#include <iostream>#include <string>#include <fstream>#include <sstream>#include <iomanip>using namespace std;class Student{public:    int id;    string name;    Student *next;    Student(int nid = 0, string nname = "noname", Student *pnext = NULL):        id(nid), name(nname), next(pnext) { }};class StuNode{    Student *head;public:    StuNode() { head = NULL; }    ~StuNode();    void linsert();    bool ldelete(int nid);    void show();    void doview();};StuNode::~StuNode(){    Student *p = head, *q;    while (p->next != NULL)    {        q = p;        p = p->next;        delete q;    }}void StuNode::linsert(){    Student *p = new Student();    cout << "请输入学号:";    cin >> p->id;    cout << "请输入姓名:";    cin >> p->name;    p->next = head;    head = p;}void StuNode::show(){    Student *p = head;    cout << setw(10) << "学号" << setw(8) << "姓名" << endl;    while (p)    {        cout << setw(10) << p->id << setw(8) << p->name << endl;        p = p->next;    }}void StuNode::doview(){    char n;    while (1)    {        cout << "1inter" << "!!" << "2show" << "!!" << "0exit" << endl;        cin >> n;        switch(n)        {        case '1':            linsert();            break;        case '2':            show();            break;        case '0':            return;        default:            break;        }    }}int main(){    StuNode s;    s.doview();    return 0;}
[解决办法]
void stunode::linsert()
{student *p=new student();
cout<<"请输入学号:";
cin>>p->id;
cout<<"请输入姓名:";
cin>>p->name;

if(!head)
{head=p;
 head->next=NULL;
_______________
没这个导致你用SHOW时链表取到最后一个时出错
}
else {
p->next=head;
head=p;
}

}

热点排行