I'm trying to convert a c program to c++ basically a struct data type to a class but is keeps showing " ‘first’ was not declared in this scope". whereas c program is working just fine.
Original code
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
}*first=NULL;
void Display(struct Node *p)
{
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
void Insert(struct Node *p,int index,int x)
{
struct Node *t;
int i;
if(index < 0 || index > 9)
return;
t=(struct Node *)malloc(sizeof(struct Node));
t->data=x;
if(index == 0)
{
t->next=first;
first=t;
}
else
{
for(i=0;i<index-1;i++)
p=p->next;
t->next=p->next;
p->next=t;
}
}
int main()
{
Insert(first,0,5);
Insert(first,1,10);
Insert(first,2,15);
Display(first);
return 0;
}
edited Code
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
void Display(struct Node *p){
while(p!=NULL){
std::cout << p->data << std::endl;
p=p->next;
}
}
void Insert(struct Node *p,int index,int x){
Node *t;
int i;
if(index < 0 || index > 9)
return;
t=new Node;
t->data=x;
if(index == 0){
t->next=first;
first=t;
}
else
{
for(i=0;i<index-1;i++)
p=p->next;
t->next=p->next;
p->next=t;
}
}
int main()
{
Node *first=NULL; //
Insert(first,1,10);
Insert(first,2,15);
Display(first);
return 0;
}
error is something related to "Node *first = Null" line something to do with global pointer Insert(first,0,5);