[英]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.