c++ implementation of a linked list.
-
Pardon me!! I am new here. I am unable to use addNode function. When i declare Node* it doesnt compile. I am trying to implement a linked list in c++ without using structures and only use pure classes.I am rusty here. Any help would be great. head->addNode() and head.addNode() doesnt work.
#include
#include
using namespace std;
class Node
{
int data;
Node* next;
public:
Node()
{
data=0;
next=NULL;
}
void addNode(int a)
{
if(this!=NULL)
{
data=a;
next=NULL;
}
}
};
void main()
{
Node* head;
head.addNode(10);
} -
Pardon me!! I am new here. I am unable to use addNode function. When i declare Node* it doesnt compile. I am trying to implement a linked list in c++ without using structures and only use pure classes.I am rusty here. Any help would be great. head->addNode() and head.addNode() doesnt work.
#include
#include
using namespace std;
class Node
{
int data;
Node* next;
public:
Node()
{
data=0;
next=NULL;
}
void addNode(int a)
{
if(this!=NULL)
{
data=a;
next=NULL;
}
}
};
void main()
{
Node* head;
head.addNode(10);
}addNode is not a member of the Node class.
class Node
{
public:
void addNode(int a);
};
void Node::addNode( int a )
{
//...
}your addNode is not good, you need to think things over; you do not allocate a new node; you do not assign the next pointer ... I find that using free functions instead of class methods makes things easier when doing this; a node only contains the data (and the next pointer). if all fails, use std::vector. Good luck.
Nihil obstat
-
Pardon me!! I am new here. I am unable to use addNode function. When i declare Node* it doesnt compile. I am trying to implement a linked list in c++ without using structures and only use pure classes.I am rusty here. Any help would be great. head->addNode() and head.addNode() doesnt work.
#include
#include
using namespace std;
class Node
{
int data;
Node* next;
public:
Node()
{
data=0;
next=NULL;
}
void addNode(int a)
{
if(this!=NULL)
{
data=a;
next=NULL;
}
}
};
void main()
{
Node* head;
head.addNode(10);
}void main()
{
Node* head;
head.addNode(10);
}Create the object in the heap first. You just declared a variable stating "I will hold address of Node object in a variable head". But, where does that object? When there is no object head-> will not work. Head.addNode() also wont work as the object is not in stack. Correction:
void main()
{
Node* head = new Node();
head->addNode(10);
}Object will be created in heap. or
void main()
{
Node head;
head.addNode(10);
}Object will allocated on stack