Delete_At链接列表的功能导致程序崩溃

时间:2014-04-21 08:03:16

标签: c++ crash linked-list nodes

我创建了一个Linked List类,一切正常但是当我运行Delete_At函数时它会崩溃! ,没有给出语法错误,它是合乎逻辑的,我真的不知道我错过了什么

这是代码:

#include <iostream>
using namespace std;



struct node{

int info;

node *link;

};


class Linked_List{


private :

int count;
node *first;
node *last;
node *current;

public:


Linked_List() {

count=0;
first=NULL;
last=NULL;
}



void Initialize_List(){

cout<<"Enter Number OF Nodes"<<endl;
cin>>count;

first=last=current=new node;

for(int i =0;i<count;i++){
cout<<"Enter New Node Info :"<<endl;
cin>>current->info;
last->link=current;
last=current;
current=new node;}
last->link=NULL;
}


void Insert_At (int loc,int element){


for (current=first;current!=NULL;current=current->link){
if (current->info==loc){

node *newnode= new node;
newnode->info=element;

newnode->link=current->link;
current->link=newnode;
count++;}
}
if(current==last){
node *newnode= new node;
newnode->info=element;

last->link=newnode;
last=newnode;
newnode->link=NULL;}
}


void Delete_At(int loc){
bool found;

node *p=new node;
if(first ==NULL)
cout<<"can't delete from empty list"<<endl;


else {
found = false ;
current=first;
p=first->link;

while (p!=NULL){

if(p->info!=loc){

current=p;
p=p->link;}

else found = true;}

if (found) {
current->link=p->link;
count--;
delete p;} }}
};

void main (){


Linked_List obj;

obj.Initialize_List();

obj.print();

obj.Insert_At(3,10); cout<<"item inserrted"<<endl;

obj.print();

obj.Delete_At(3);  cout<<"item deleted"<<endl;   //lets say i have  number 3 in my 
list.

obj.print();

}

1 个答案:

答案 0 :(得分:1)

你的while循环循环,直到p为NULL,即使找到了节点。然后,当p保证为NULL时,您会立即在current->link=p->link行中取消引用p

找到正确的节点后,您需要突破while循环。将&& !found放入while子句就可以了。

请注意,由于缺少缩进,这更难以发现,我不知道这是否是由于剪切和粘贴,或者是否是您编写它的方式。