【发布时间】:2014-12-14 17:21:49
【问题描述】:
在一个简单的 LinkedList 类中,我试图删除一个对象,当该项目存在时它工作正常,但是当我尝试删除一个不存在的项目时,我的程序终止并说它刚刚停止工作......下面发布的是代码。有什么建议吗?
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(){
data=-1;
next=NULL;
}
Node(int d){
data=d;
next=NULL;
}
Node(int d, Node* n){
data=d;
next=n;
}
};
class LinkedList{
public:
Node* head;
Node* dummy = new Node();
LinkedList(){
head=dummy;
}
LinkedList(Node* n){
head=dummy;
dummy->next=n;
}
void ins(Node* n){
Node* current = head;
while(current->next!=NULL&¤t->next->data<=n->data){
current=current->next;
}
n->next=current->next;
current->next=n;
}
void print(){
Node* current = head;
while(current->next!=NULL){
cout<<current->next->data<<endl;
current=current->next;
}
}
int peek(){
if(head->next==NULL){
cout<<"List is Empty"<<endl;
}
return head->next->data;
}
void rem(int toRemove){
Node* current = head;
while(current->next!=NULL&¤t->next->data!=toRemove){
current=current->next;
}
if(current->next->data==toRemove){
current->next=current->next->next;
cout<<"Removing Item"<<endl;
return;
}
if(current->next->data!=toRemove){
cout<<"No Item Found"<<endl;
return;
}
if(current->next==NULL){
cout<<"Not Removable since not there"<<endl;
return;
}
}
};
int main(){
LinkedList* a = new LinkedList();
Node* n = new Node(5);
Node* nn = new Node(10);
Node* nnn = new Node(15);
Node* nnnn = new Node(12);
Node* nnnnn = new Node(7);
a->ins(n);
a->ins(nn);
a->ins(nnn);
a->ins(nnnn);
a->ins(nnnnn);
a->print();
a->rem(5);
a->print();
a->rem(13);
a->print();
return 0;
}
感谢任何帮助。谢谢,
【问题讨论】:
-
我的建议是你在调试器中运行。
-
我还建议您再次查看您的逻辑,包括循环和之后的检查。你认为当循环运行到结束时(当第一个条件为真时)会发生什么,因为找不到该项目?
-
你为什么需要一个虚拟节点?
-
Dummy 可以减少插入和删除的情况