Hi so I am just trying to figure out what is wrong with my program. I am trying to implement the node class in C++. All I want to do is learn how to implement it and get it working. I am not trying to use it to create a list class, I just want to learn how to work with linked lists and the node class for certain interview questions. Anyways I seem to have a problem with my next pointer. When I insert a new node it seems to work as I kept a length field to see if its working and the length is incremented but I must be doing something wrong with the next and front pointers. Please help, let me know what I may be doing wrong
#ifndef NODE_H_
#define NODE_H_
#include <iostream>
using namespace std;
template <class T>
class node {
public:
int length;
T nodeValue;
node<T> *front, *next;
// Default constructor
node(): next(NULL), front(NULL), length(0)
{}
// Constructor. Initialize nodeValue and next.
node(const T& item, node<T> *nextNode = NULL):
nodeValue(item), next(nextNode)
{}
// Add a new node
void addNodeAtFront(const T& value);
virtual ~node();
};
template <typename T>
void node<T>::addNodeAtFront(const T& value){
node<T> *newNode;
newNode = new node<T>(value,next);
if (front == NULL){
// Set the new node to be the front
front = newNode;
if (newNode->next == NULL)
cout<<"newNode->next is NULL"<<endl;
//cout<<newNode<<endl;
length++;
}
else {
// Set the new node to point at the next node
newNode->next = front;
// Set the new node to be the 'front'
front = newNode;
//cout<<newNode<<endl;
length++;
}
}
template <typename T>
node<T>::~node() {
// TODO Auto-generated destructor stub
}
#endif /* NODE_H_ */
Here is the main program
#include <iostream>
#include "node.h"
using namespace std;
int main(){
node<int> *p;
p = new node<int>(5);
cout<<"Here is your value: "<<p->nodeValue<<endl;
for (int i = 0; i < 10; i++)
p->addNodeAtFront(i);
cout<<"p->length is: "<<p->length<<endl;
if (p->next == NULL)
cout<<"P->next is NULL"<<endl;
else
cout<<"P->next is not NULL"<<endl;
return 0;
}
I had some code to write the list i.e.
while (P != NULL){
cout<<p->nodeValue<<endl;
p = p->next;
}
but I erased it and that's is why I added the check to see if p->next is NULL and it is.
here is the output:
Here is your value: 5
newNode->next is NULL
p->length is: 10
P->next is NULL