簡體   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