Output not coming and has few errors

#include
using namespace std;
int insertatbeg(int data,struct node *head,struct node newnode);//function declaration
int main(){
struct node{
int data;
struct node
next;
};

int choice=1;
struct nodehead=NULL,newnode,temp;
while(choice){
newnode=(struct node
)malloc(sizeof(struct node));
cin>>newnode->data;
newnode->next=0;
if(head==0)
{
head=temp=newnode;
}
else {
newnode->next = head;
head = newnode;
}
cout<<“do you want to continue”<<endl;
cin>>choice;
}
temp=head;
while(temp!=0)
{
cout<data;//printing linkedlist
temp=temp->next;
}
insertatbeg(data,head,newnode);//function calling
cout<data;//printing data of new node at first
temp=head;//now printing the previous linked list followed by newnode
while(temp!=0)
{
cout<data;
temp=temp->next;
}
}
int insertatbeg(int data, struct node
head,struct node
newnode)//function defination
{
cin>>newnode->data;
newnode->next=head;
head=newnode;
}
/Errors:
main.cpp: In function ‘int main()’:
main.cpp:33:13: error: ‘data’ was not declared in this scope
insertatbeg(data,head,newnode);//function calling
^~~~
main.cpp: In function ‘int insertatbeg(int, node
, node*)’:
main.cpp:44:17: error: invalid use of incomplete type ‘struct node’
cin>>newnode->data;
^~
main.cpp:3:33: note: forward declaration of ‘struct node’
int insertatbeg(int data,struct node *head,struct node *newnode);//function declaration
^~~~
main.cpp:45:12: error: invalid use of incomplete type ‘struct node’
newnode->next=head;
^~
main.cpp:3:33: note: forward declaration of ‘struct node’
int insertatbeg(int data,struct node *head,struct node *newnode);//function declaration
^~~~
*/

Hi @supratik260699
Few changes you have to make in your code.

  1. first of all as you are writing a function outside the main function scope so you need to define you class node also outside the main function.
  2. because your function is to add a value at the beg. of the list so instead of int the return type of you function should be struct node *.
  3. before sending newnode to function you should first assign memory to it.
  4. and data has no use in function so you should not use it.

After changing the above things you code looks like :

1 Like