C++链表有关问题
C++链表问题
"list.h "
#ifndef LIST_H
#define LIST_H
#include <iostream.h>
#include <conio.h>
struct person
{
char name[20];
char num[20];
};
struct Node
{
struct person pe;
Node *next;
};
class list
{
public:
list(){head=NULL;}
Node* setlastnode();
void Creat();
void display();
void deletenode();
private:
Node *head;
};
#endif
"list.cpp "
#include "List.h "
Node* list::setlastnode()
{
Node* p;
p=head;
while(p!=NULL)
{
p=p-> next;
}
p=new Node;
return p;
}
void list::Creat()
{
Node* p;
if(head==NULL)
{
head=new Node;
p=head;
}
else
p=list::setlastnode();
cout < < "请输入姓名: ";
cin> > p-> pe.name;
cout < < "请输入学号: ";
cin> > p-> pe.num;
}
void list::display()
{
int i=1;
Node *p=head;
while(p!=NULL)
{
cout < < "第 " < <i < < " 个学生\n " < < "姓名: ";
cout < <p-> pe.name < <endl;
cout < < "学号: " < <p-> pe.num < <endl;
p=p-> next;
i++;
}
}
void list::deletenode()
{
Node* p;
while(head!=NULL)
{
p=head;
head=head-> next;
delete p;
}
}
"main.cpp "
#include "List.h "
void main()
{
list a;
int i=1;
while(i)
{
a.Creat();
cout < < "退出按 ESC 其它继续 " < <endl;
i=getch();
switch(i)
{
case 27:
i=0;
break;
default:
i=1;
}
}
a.display(); //显示
a.deletenode(); //释放内存
}
编译没有问题 但是运行时 程序会死掉,不知道是什么原因
还有 不知道这样释放内存是否正确
------解决方案--------------------
/*
Node* list::setlastnode()
{
Node* p;
"list.h "
#ifndef LIST_H
#define LIST_H
#include <iostream.h>
#include <conio.h>
struct person
{
char name[20];
char num[20];
};
struct Node
{
struct person pe;
Node *next;
};
class list
{
public:
list(){head=NULL;}
Node* setlastnode();
void Creat();
void display();
void deletenode();
private:
Node *head;
};
#endif
"list.cpp "
#include "List.h "
Node* list::setlastnode()
{
Node* p;
p=head;
while(p!=NULL)
{
p=p-> next;
}
p=new Node;
return p;
}
void list::Creat()
{
Node* p;
if(head==NULL)
{
head=new Node;
p=head;
}
else
p=list::setlastnode();
cout < < "请输入姓名: ";
cin> > p-> pe.name;
cout < < "请输入学号: ";
cin> > p-> pe.num;
}
void list::display()
{
int i=1;
Node *p=head;
while(p!=NULL)
{
cout < < "第 " < <i < < " 个学生\n " < < "姓名: ";
cout < <p-> pe.name < <endl;
cout < < "学号: " < <p-> pe.num < <endl;
p=p-> next;
i++;
}
}
void list::deletenode()
{
Node* p;
while(head!=NULL)
{
p=head;
head=head-> next;
delete p;
}
}
"main.cpp "
#include "List.h "
void main()
{
list a;
int i=1;
while(i)
{
a.Creat();
cout < < "退出按 ESC 其它继续 " < <endl;
i=getch();
switch(i)
{
case 27:
i=0;
break;
default:
i=1;
}
}
a.display(); //显示
a.deletenode(); //释放内存
}
编译没有问题 但是运行时 程序会死掉,不知道是什么原因
还有 不知道这样释放内存是否正确
------解决方案--------------------
/*
Node* list::setlastnode()
{
Node* p;