Nikhil Chilwant
Nikhil Chilwant

Reputation: 649

creating doubly linked list

I want to just create the doubly linked list and check if it is empty. Please tell the mistake. ERROR shown is : In function empty(), head and tail are out of scope. Didn't work when define as struct in class 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;}
}

Upvotes: 1

Views: 3368

Answers (3)

McKay
McKay

Reputation: 12604

I think you just need to include the empty method in your class:

bool Dict::empty()
{
    return head->next==tail;
}

Upvotes: 2

Juniar
Juniar

Reputation: 1389

  • There are a couple of things you need to work on. First you did not include your node.cpp there is only node.h, what does your node constructor do? On the Dict() constructor you should call node constructor i.e node() this will initialize the node class to whatever your node constructor does i.e set the variable string data to some input value.
  • What is the empty() output. According to your definition. empty() method, is doing the same thing, checking if head->next is sitting at the same memory location with the tail. I dont think thats what you want, because it will always return true if you call dict() constructor. If you don`t call dict() it will return false or you might even get an handle error, "null reference".
  • To create a list of nodes or linked list, You need to define ADD method, this method should be able to add a new node or link the current node with the next node.
  • You also need to define remove node, that removes or delete any given node. This will probably be the hardest method you have written so far.

Upvotes: 0

McKay
McKay

Reputation: 12604

Well, first off, you're not creating an empty list, because your constructor creates new nodes.

In your "empty" method, you're trying to reference a "head" variable definied in the Dict class

possible fix:

Dict::Dict()
{
    head = tail = null;
}

bool Dict::empty()
{
    return head == null;
}

Upvotes: 1

Related Questions