我的存在方法有问题。
我去列表中查找一个int,如果它在列表中它可以工作,但如果没有它不会工作,我得到一个运行时错误,说它停止工作。
有一个类列表,其中包含两个类:Node和Iterator。
代码在这里。
class List {
private:
class Node {
public:
Node(int d, Node *n = NULL, Node *p = NULL)
: data(d), next(n), prev(p) {}
int data;
Node *next;
Node *prev;
};
public:
class Iterator {
public:
int next_element() {
int to_be_returned = current->data;
current = current->next;
return to_be_returned;
}
bool has_more_elements() {
return current != NULL;
}
private:
Node *current;
Iterator(Node* n) { current = n; }
friend class List;
};
public:
List();
~List();
void print();
void push_front(int x);
void push_back(int x);
void clear();
bool exists(int x);
Iterator get_iterator() {
return Iterator(_head);
}
private:
Node* _head;
Node* _last;
};
List::List() {
_head = NULL;
_last = NULL;
}
void List::print() {
for (Node* p = _head; p != NULL; p = p->next)
cout << p->data << ' ';
}
void List::push_front(int x) {
Node *new_node = new Node(x);
new_node->next = _head;
if (_head != NULL)
_head->prev = new_node;
_head = new_node;
if (_last == NULL)
_last = new_node;
}
void List::push_back(int x) {
if (_head == NULL)
push_front(x);
else {
Node *new_node = new Node(x);
new_node->prev = _last;
_last->next = new_node;
_last = new_node;
}
}
List::~List() {
clear();
}
void List::clear() {
Node *p = _head;
while (p != NULL) {
Node *q = p;
p = p->next;
delete q;
}
_head = NULL;
_last = NULL;
}
bool List::exists(int x){
Iterator it = this->get_iterator();
while(it.current->data!=x && it.has_more_elements())
it.current=it.current->next;
return (it.current->data==x)?true:false;
}
这是我的主要()
int main() {
List l;
l.push_back(86);
l.push_front(43);
l.push_front(12);
if(l.exists(1)){
cout<<"t";
}
else{
cout<<"f";
}
}
答案 0 :(得分:1)
在访问指针指向的数据之前,您应检查指针是否指向nullptr (请参阅has_more_elements()
)。更好的命名可以避免一些混淆。
答案 1 :(得分:0)
while(it.current->data!=x && it.has_more_elements())
it.current=it.current->next;
return (it.current->data==x)?true:false;
如果x
不存在且it
到达列表末尾,it.current->data
将导致运行时错误,因为it
可能是NULL
。
while(it.has_more_elements() && it.current->data!=x)
it.current = it.current->next;
return it.current!=NULL;