Apr 3, 2013 at 4:28am UTC
Can you help me please, I cannot understand why node insertion method in this circular list is not working. There is no error at time of compilation and execution but the output displays that the values of nodes added in the list are zero.
#include<iostream.h>
#include<stdlib.h>
class Node {
public:
int get() { return object; };
void set(int object) { this->object = object; };
Node* getNext() { return nextNode; };
void setNext(Node* nextNode)
{ this->nextNode = nextNode; };
Node* getPrev() { return prevNode; };
void setPrev(Node* prevNode)
{ this->prevNode = prevNode; };
private:
int object;
Node* nextNode;
Node* prevNode;
};
class List
{
public:
List();
void add (int addObject);
void remove();
int get();
int length();
bool next();
Node start();
friend void traverse(List list);
friend List addNodes();
private:
int size;
Node * headNode;
Node * currentNode;
Node * lastCurrentNode;
};
List::List()
{
headNode = new Node();
headNode->setNext(NULL);
headNode->setPrev(NULL);
currentNode = NULL;
lastCurrentNode = NULL;
size = 0;
}
void List::add (int addObject)
{
Node * newNode = new Node();
newNode->set(addObject);
if( currentNode != NULL )
{
newNode->setNext(currentNode->getNext());
newNode->setPrev(currentNode);
currentNode->setNext( newNode );
(currentNode->getNext())->setPrev(newNode);
lastCurrentNode = currentNode;
currentNode = newNode;
}
else
{
newNode->setNext(headNode);
newNode->setPrev(headNode);
headNode->setNext(newNode);
headNode->setPrev(newNode);
lastCurrentNode = headNode;
currentNode = newNode;
}
size ++;
}
int List::get()
{
if (currentNode != NULL)
return currentNode->get();
}
int List::length()
{
return size;
}
bool List::next()
{
if (currentNode == NULL) return false;
lastCurrentNode = currentNode;
currentNode = currentNode->getNext();
if (currentNode == NULL || size == 0)
return false;
else
return true;
}
void traverse(List list)
{
Node* savedCurrentNode = list.currentNode;
list.currentNode = list.headNode;
do
{
for(int i=0;i<list.size;i++)
cout << "\n Element " << i << " " << list.get();
}
while(list.currentNode!=list.headNode);
list.currentNode = savedCurrentNode;
}
void List:: remove()
{
if (currentNode!=NULL||currentNode!=headNode)
{
lastCurrentNode->setNext(currentNode->getNext());
(currentNode->getNext())->setPrev(lastCurrentNode);
currentNode=currentNode->getNext();
delete currentNode;
}
}
Node List:: start()
{
lastCurrentNode = headNode;
currentNode = headNode;
}
List addNodes()
{
List list;
list.add(2);
list.add(6);
list.add(8);
list.add(7);
list.add(1);
cout << "\n List size = " << list.size <<'\n';
return list;
}
main()
{
List list = addNodes();
traverse(list);
}
Last edited on Apr 3, 2013 at 4:29am UTC
Apr 3, 2013 at 7:56am UTC
check your traverse function. list is always pointing to the same node.