following is C++ written linked list with Node class and main function. List is traversing forward using "next()" function but producing execution time error when traverse back using "back()".
#include <iostream>
using namespace std;
class Node {
public:
int object;
Node *nextNode;
Node *prevNode;
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;
}
};
class List {
public:
Node* headNode;
Node* currentNode;
int size;
public:
List(){
headNode = new Node();
headNode->setNext(NULL);
headNode->setPrev(NULL);
currentNode = NULL;
int size = 0;
}
void add(int addObject){
Node* newNode = new Node();
newNode->set(addObject);
if(currentNode != NULL){
newNode->setNext(currentNode->getNext());
newNode->setPrev(currentNode);
currentNode->setNext(newNode);
currentNode = newNode;
}
else {
newNode->setNext(NULL);
newNode->setPrev(headNode);
headNode->setNext(newNode);
currentNode = newNode;
}
size++;
}
int get(){
if(currentNode != NULL) {
return currentNode->get();
}
}
bool next(){
if(currentNode == NULL) return false;
currentNode = currentNode->getNext();
if(currentNode == NULL) return false;
else return true;
}
bool back(){
if(currentNode == NULL) return false;
currentNode = currentNode->getPrev();
if(currentNode == NULL) return false;
else return true;
}
void start(){
currentNode = headNode;
}
void remove() {
if (currentNode != NULL && currentNode != headNode){
delete currentNode;
size--;
}
}
int length() {
return size;
}
};
int main(){
List list;
list.add(5);
list.add(13);
list.add(4);
list.add(8);
list.add(48);
list.add(12);
list.start();
while(list.next()){
cout<<endl<<"Element: " << list.get() << endl;
}
cout<<endl<<"BACK"<<endl;
while(list.back()){
cout<<endl<<"Element: " << list.get() << endl;
}
}
Back() function should traverse the list in opposite direction (from end to start).. reverse manner. Sometime this code hangs the CPU and sometimes it only runs next() function, and for back() function it remains silent without doing anything.