创建双链表

creating doubly linked list

本文关键字:链表 创建      更新时间:2023-10-16

我只想创建双链接列表并检查它是否为空。请把错误告诉我。显示的错误是:在函数empty()中,头和尾超出了范围。在Dict.类中定义为结构时不起作用

#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;
}

首先,您不会创建一个空列表,因为您的构造函数会创建新的节点。

在"empty"方法中,您试图引用Dict类中定义的"head"变量

可能的解决方案:

Dict::Dict()
{
    head = tail = null;
}
bool Dict::empty()
{
    return head == null;
}
  • 有几件事你需要做。首先你没有包括你的node.cpp,只有node.h,你的节点构造函数做什么?在Dict()构造函数上,您应该调用节点构造函数,即node(),这将把节点类初始化为您的节点构造函数所做的任何事情,即将变量字符串数据设置为某个输入值
  • empty()的输出是什么。根据你的定义。empty()方法,正在做同样的事情,检查head->next是否与tail位于同一内存位置。我不认为t think that是您想要的,因为如果您调用dict()构造函数,它将始终返回true。如果你不调用dict(),它将返回false,或者你甚至可能得到一个句柄错误,"null引用"
  • 要创建节点列表或链表,您需要定义ADD方法,该方法应该能够添加新节点或将当前节点与下一个节点链接
  • 您还需要定义删除节点,用于删除或删除任何给定的节点。这可能是迄今为止你写过的最难的方法