Doubly Linked list.......Real Confusion

Oct 21, 2010 at 8:40pm
I am trying to write the code for double linked list........it works fine for a single linked but not for double.
I have bolded the line that is the cause of the error but I am out of ideas about how to correct it. Plz guide me in this matter

#include<iostream.h>
#include<conio.h>

// Node Class
class Node
{
public:
void set(int);
int get();
void setNext(Node *);
Node *getNext();
void setPrev(Node *);
Node *getPrev();


private:
int object;
Node *nextNode;
Node *prevNode;
};

void Node::set(int object)
{
this->object = object;
}

int Node::get()
{
return object;
}

void Node::setNext(Node *nextNode)
{
this->nextNode = nextNode;
}

Node *Node::getNext()
{
return nextNode;
}

void Node::setPrev(Node *prevNode)
{
this->prevNode = prevNode;
}

Node *Node::getPrev()
{
return prevNode;
}


class List
{
public:
List();
void start();
void add(int);
int get();
bool next();


private:
Node *headNode;
Node *currentNode;
int size;

};


// List Class
List::List()
{
headNode = new Node;
headNode->setNext(NULL);
headNode->setPrev(NULL);
currentNode = NULL;
size = 0;
}

void List::start()
{
currentNode = headNode;
}

void List::add(int addObject)
{
Node *newNode = new Node;
newNode->set(addObject);
if ( currentNode != NULL )
{
newNode->setNext(currentNode->getNext());
newNode->setPrev(currentNode);
(currentNode->getNext())->setPrev(newNode);
currentNode->setNext(newNode);
currentNode = newNode;
}
else
{
newNode->setNext(NULL);
newNode->setPrev(headNode);
headNode->setNext(newNode);
headNode->setPrev(NULL);
currentNode = newNode;
}
size++;
}


int List::get()
{
if(currentNode != NULL)
{
return currentNode->get();
}
}


bool List::next()
{
if (currentNode == NULL)
{
return false;
}
currentNode = currentNode->getNext();
if( (currentNode == NULL)||(size = 0) )
{
return false;
}
else
{
return true;
}
}




// main body
main()
{
List list;
list.add(3);
list.add(4);
list.add(6);
list.add(5);

while(list.next())
{
cout << list.get() << endl;
}

getch();
}
Oct 22, 2010 at 11:41am
Hello saad danger,

I didn't review the whole code though
considering that bold line, you should check whether currentNode->getNext() returns NULL. in that case you don't need to set the pevious.

Do you know that stl has already a double linked list?
Oct 23, 2010 at 5:24pm
hi thx for reply wht u mean by this......
"Do you know that stl has already a double linked list?"
Oct 23, 2010 at 7:28pm
look at this for the st list: http://www.cplusplus.com/reference/stl/list/

I forgot to say: if currentNode->getNext() returns NULL your prgramm crashes like you experienced it so write

1
2
if(currentNode->getNext())
  (currentNode->getNext())->setPrev(newNode);

Topic archived. No new replies allowed.