Reputation: 327
I am trying to make a two way linked-list in c++ with class but I have a annoying problem to add node to the first of the list!
Here is Node
class:
class node{
public:
node(int d = 0, node *p = NULL, node *n = NULL):data(d), pre(p), next(n){}
void setPrevious(node *p){this->pre = p;}
void setNext(node *n){this->next = n;}
void setData(int d){this->data = d;}
int data;
node *pre, *next;
};
Here is how I create the first Node:
node *head = new node(), *current = new node(), *last = new node();
cout<<msg_data;
// 'd' is an Integer variable
cin>>d;
current->setData(d);
head = new node(0, 0, current);
And this is how I try to add node to the first of the list:
cout<<"enter 'data' for list: ";
// 'd' is an Integer variable
cin>>d;
node *tmp = new node(d, 0, head);
head = tmp;
When I want to add node to first it add a '0' for 'data' after a value! ex. I want to add '21' to the first of the list but it adds 21 and 0 to the list!
Upvotes: 1
Views: 98
Reputation: 1869
Two observations:
Looking at your code that creates the first node it creates not one node but FOUR nodes. It seems you completely misunderstood something. Draw on paper how the list should look, and you will figure it out.
Your code that adds an extra node to the first of the list seems OK.
Upvotes: 1