[求助]我这个单链表程序一执行删除操作就非法操作!大家帮我看看!!
我这个单链表程序一执行删除操作就非法操作!大家帮我看看!! 快交作业了!!急!!!
#include<iostream.h>
#include<stdlib.h>
class List; //List类的前视声明
class Node
{
friend class List; //将List类声明为Node类的友元
private: //私有成员
int data;
Node *next;
};
class List
{
public:
List() //成员函数
{
head=NULL;
cnt=0;
}
void count(); //计算结点个数
void insert(int x);
void remove();
void display();
Node *head; //定义链表头结点,数据成员
int cnt;
};
void List::count()
{
cout<<"The Length of the Linklist is "<<cnt<<endl;
}
void List::insert(int x) //后插法向链表插入元素
{
cout<<"Please Input the Data you want to Insert(Type 0 to Finish):";
cin>>x;
while (x!=0)
{ Node *currPtr=new Node; //建立一个新结点,并使用指针currPtr指向它
Node *tempPtr; //定义临时指针
cnt++;//计数加一
if(!currPtr)
{
cout<<"Out Of Memory"<<endl;
}
currPtr->data=x;//将x赋给指针currPtr指向结点的data
currPtr->next=NULL;//将NULL赋给指针currPtr指向结点的next
if(head==NULL) //检测是否是空表
head=currPtr;
else
{
tempPtr=head;
while(tempPtr->next!=NULL)
tempPtr=tempPtr->next;
tempPtr->next=currPtr;
}
cout<<"Please Input the Data you want to Insert(Type 0 to Finish):";
cin>>x;
}
}
void List::display()//输出链表中的数据
{
if(!head)
cout<<"The LinkList is empty!"<<endl;
else{
cout<<"The Node in the LinkList are: ";
int i=0;
Node *currPtr=head;
while(i<cnt)
{
cout<<" ["<<i<<"] "<<currPtr->data<<"->";
currPtr=currPtr->next;
i++;
}
cout<<endl;
}
}
void main()
{
List list;
list.count();
list.display();
int x(NULL);
list.insert(x);
list.count();
list.display();
}