I wrote the following code, to just create and insert nodes (integer data) into an SLL, in C++.
#include <stdio.h>
class Node
{
public:
int data;
Node * next;
Node * first;
Node() {}
void insert(int dat)
{
Node * newnode = new Node();
newnode->data=dat;
newnode->next=NULL;
if(first==NULL)
{
first=newnode;
}
else
{
Node *temp=first;
while(temp->next!=NULL)
{ temp=temp->next; }
temp->next=newnode;
}
}
};
int main()
{
Node * a=new Node();
a->insert(12);
return 0;
}
At first, I tried overriding the Node constructor to Node(int dat) and in that I tried doing initialization of every new node (data=dat, next=NULL) that I create in insert. Insert would be called with a "dat" value from main and it would call the overloaded Node constructor to initialize data to dat and next to NULL. That led to my program crashing.
So I took out both default and overloaded constructor and did the initialization of each new element in the insert itself. My program works fine. However, even adding the default constructor (as shown in Line 10 of the code) my program crashes. Can anyone tell me why this is happening in both cases?
Thanks.
firstpointer in every node? Normallyfirstis a member of the singly-linked list but not of the node. Besides that you never initializefirstand the comparison (first == NULL) might trigger or might not.