[英]creating doubly linked list
我想创建双向链表并检查它是否为空。 请说出错误。 显示的错误是:在函数empty()中,head和tail超出范围。 在类Dict中定义为struct时不起作用。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class node
{ public:
string data;
node* next;
node* prev;
friend class Dict;
};
class Dict
{ public:
bool empty();
Dict();
node* head;
node* tail;
};
Dict::Dict()
{ head=new node;
tail= new node;
head->next=tail;
tail->prev=head;
}
bool empty()
{
return head->next==tail;
}
int main()
{
Dict my_list;
if(my_list.empty())
{cout<<"empty list"<<endl;}
else
{cout<<"Not empty"<<endl;}
}
我想你只需要在你的类中包含空方法:
bool Dict::empty()
{
return head->next==tail;
}
好吧,首先,你没有创建一个空列表,因为你的构造函数创建了新的节点。
在你的“空”方法中,你试图引用在Dict类中定义的“head”变量
可能的修复:
Dict::Dict()
{
head = tail = null;
}
bool Dict::empty()
{
return head == null;
}
t think that
你想要的是什么,因为如果你调用dict()构造函数它将永远返回true。 如果你不调用dict(),它将返回false,或者你甚至可能得到一个句柄错误,“null reference”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.