我一用 delete 就运行出错,何解?
chl 2001-11-29 05:16:23 小弟做C++还是新手,做了个简单的链表,虽然插入、删除、等功能都实现了,但发现只要我的代码中一出现,如下注释了的 delete .. 就运行时报错了,请指点。
#include<iostream.h>
class Node
{
char* mesg;
Node* nextNode;
public :
Node(char* msg);
void setNode(Node* n);
Node* getNode();
char* getMesg();
~Node();
};
char* Node::getMesg(){
return mesg;
}
void Node::setNode(Node* n){
nextNode=n;
}
Node* Node::getNode(){
return nextNode;
}
Node::Node(char* msg)
{
mesg=msg;
nextNode=NULL;
}
Node::~Node(){
delete mesg;
delete nextNode;
cout<<"\n**node delet**\n";
}
// List started.
class List
{
Node* head,* tail;
unsigned int nCount;
void remove(Node* n);
public :
List();
int nodeCount();
void insert(unsigned int count,Node* n);
void add(Node* n);
void removeAll();
void delet(unsigned int count);
void show();
~List();
};
List::List(){
head=new Node("It's head here.");
tail=head;
head->setNode(NULL);
nCount=0;
}
List::~List(){
delete head;
delete tail;
cout<<"\n**delete List**\n";
}
void List::add(Node* n){
if(nCount==0){
head->setNode(n);
tail=n;
}
else{
tail->setNode(n);
tail=n;
}
tail->setNode(NULL);
nCount++;
}
void List::insert(unsigned int count,Node* n){
if(count==0){
cout<<"只从1开始。"<<endl;
return ;
}
if(count>nCount+1){
cout<<"没有那么多个节点。"<<endl;
return ;
}
if(count!=nCount+1){
Node* node=head;
for(unsigned int i=1;i<count;i++){
node=node->getNode();
}
n->setNode(node->getNode());
node->setNode(n);
List::nCount++;
}
else{List::add(n);}
}
void List::delet(unsigned int count){
if(count==0){
cout<<"从1开始。"<<endl;
return ;
}
if(count>nCount){
cout<<"没有那么多个节点。"<<endl;
return ;
}
if(count!=nCount){
Node* node=head;
for(unsigned int i=1;i<count;i++){
node=node->getNode();
}
Node* nn=node->getNode();
node->setNode(nn->getNode());
//delete nn;
nCount--;
}
else{
Node* node=head;
for(unsigned int i=1;i<nCount;i++){
node=node->getNode();
}
Node* nn=tail;
tail=node;
tail->setNode(NULL);
//delete nn;
nCount--;
}
}
void List::removeAll(){
tail=head;
List::remove(head->getNode());
nCount=0;
tail->setNode(NULL);
}
void List::remove(Node* n){
if(n->getNode()!=NULL) {
remove(n->getNode());
}
//delete n;
}
void List::show(){
if(head->getNode()==NULL){
cout<<"Nothing in it.\n";
return;
}
Node* n=head->getNode();
cout<<"\n";
while(n!=NULL){
cout<<" "<<n->getMesg();
n=n->getNode();
}
cout<<"\n\n";
}
//class finished, main method then.
main(){
List* l;
l=new List();
l->show();
Node * n1=new Node("1");
l->add(n1);
l->add(new Node("2"));
l->insert(3,new Node("3"));
l->show();
l->delet(3);
l->show();
l->removeAll();
l->show();
//delete n1;
//delete l;
return 1;
}