The first example is the example of a linked list without dynamic memory allocation. But in this example when we run it, it will only display 10 and then will provide runtime error. Please help me finding what is wrong.
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
}Node;
struct Node* head;
void Insert(int x)
{
struct Node* temp;
temp=head;
struct Node* newnode;
newnode->data=x;
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
return;
}
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
}
void print()
{
struct Node* temp;
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
head=NULL;
Insert(10);
Insert(20);
Insert(30);
print();
}
In the below example, I have just used malloc to provide dynamic memory to the variables. It works perfectly as expected. Why is there such a difference between the two?
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
}Node;
struct Node* head;
void Insert(int x)
{
struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
temp=head;
struct Node* newnode=(struct Node*)malloc(sizeof(struct Node));
newnode->data=x;
newnode->next=NULL;
cout<<"Reached here"<<endl;
if(head==NULL)
{
head=newnode;
return;
}
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
}
void print()
{
struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
head=NULL;
Insert(10);
cout<<"Inserted 10"<<endl;
Insert(20);
cout<<"2nd"<<endl;
Insert(30);
cout<<"3rd"<<endl;
print();
}