繁体   English   中英

创建双重链表

[英]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;
}
  • 您需要处理几件事情。 首先你没有包含你的node.cpp只有node.h,你的节点构造函数做了什么? 在Dict()构造函数中,您应该调用节点构造函数,即node(),这会将节点类初始化为您的节点构造函数所做的任何操作,即将变量字符串数据设置为某个输入值。
  • 什么是empty()输出。 根据你的定义。 empty()方法正在做同样的事情,检查head-> next是否与尾部位于同一个内存位置。 我不t think that你想要的是什么,因为如果你调用dict()构造函数它将永远返回true。 如果你不调用dict(),它将返回false,或者你甚至可能得到一个句柄错误,“null reference”。
  • 要创建节点列表或链表,需要定义ADD方法,此方法应该能够添加新节点或将当前节点与下一个节点链接。
  • 您还需要定义删除节点,删除或删除任何给定节点。 这可能是你迄今为止写的最难的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM