#include "stdafx.h"
#include <iostream>
using namespace std;
class node{ //声明节点的类
public:
int num;
node *pointer;
};
class link{ //存储头节点和尾节点的类
public:
link();//链表构造函数
bool empty();//检测链表是否为空
bool search(int);//检测节点是否属于链表
void addtofront(int);//在链表头部添加节点
void addtoback(int);//在链表尾部添加节点
void deletenum(int);//在链表中删除某个点
friend ostream & operator <<(ostream &,link);//重载<<运算符
protected:
node *first; //定义链表的头节点
node *last; //定义指向最后一个节点指针
};
link::link(){first=last=0;}
bool link::empty(){ //定义函数,该函数检查链表是否为空
if(first==0)
return true;
else
return false;
}
bool link::search(int a){//定义函数,该函数检测某个数是否在链表内
node *p=first;
while(p->pointer!=0){
if(p->num==a)
return true;
p=p->pointer;
}
return false;
}
void link::addtofront(int a){//定义函数,该函数在链表首添加节点
node *p;
p=new node;
p->num=a;
p->pointer=0;
if(first==0)
first=last=p;
else{
p->pointer=first;
first=p;
}
}
void link::addtoback(int a){//定义函数,该函数在链表末添加节点
node *p;
p=new node;
p->num=a;
p->pointer=0;
if(first==0)
first=last=p;
else
{
if(first==last){
first->pointer=p;
last=p;
}
else{
last->pointer=p;
last=p;
}
}
}
ostream & operator<<(ostream & out,link biao){
node *p=biao.first;
for(;p->pointer!=0;p=p->pointer)
out<<p->num<<" ";
out<<biao.last->num<<endl;
return out;
}
void link::deletenum(int a){//定义函数,该函数删除链表中的某个点
node *p=0,*t=0;
if(empty())
cout<<"警告:该链表为空,此操作无效!!"<<endl;
else{
if(first->num==a){
p=first;
first=first->pointer;
delete p;
}
else{
t=p=first->pointer;
for(;p->num!=a && p->pointer!=0;p=p->pointer){t=p;}
if(p->pointer==0)
if(p->num!=a)
cout<<"链表中不存在该点."<<endl;
else{
t->pointer=0;
delete p;
last=t;
}
else{
t->pointer=p->pointer;
delete p;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
link list;
list.addtoback(30);
list.addtoback(40);
list.addtoback(50);
list.addtoback(80);
list.addtoback(20);
list.addtoback(10);
list.addtofront(100);
list.addtofront(200);
list.addtofront(300);
list.addtofront(400);
list.addtofront(1000);
list.deletenum(100); //*******************
if(list.search(1000))
cout<<"该点在链表中"<<endl;
else
cout<<"该点不在链表中"<<endl;
cout<<list;
return 0;
}
这个程序为什么在删除链表中第二个节点的时候会出错,而删除其他节点的时候都可以运行.
帮忙找下原因,谢谢!