2 / 2
Aug 2018

#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;}*ptr,*head=NULL;
char ch;

void create()
{
printf("\nEnter the value");
scanf("%d",&ptr->data);
if(head==NULL)
{
head=ptr;
ptr=head->next;
}
else
ptr=ptr->next;
printf("\nadd another node\n");
scanf(" %c",&ch);
if(ch==‘y’)
create();
return;
}

void print()
{
system(“cls”);
ptr=head;
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->next;
}
return;
}

int main(){
ptr=(struct node*)malloc(sizeof(struct node));
create();
print();
return 0;
}

The above code is not running in codeblocks. Please point out my mistake.

  • created

    Aug '18
  • last reply

    Aug '18
  • 1

    reply

  • 769

    views

  • 2

    users

I think the main problem is that you’re not allocating memory for the second and subsequent items in the list.

It’s not a good idea to have a recursive method to add an item to the list. Imagine if you needed to add a million entries? It’d be a better program structure to move the I/O to the main body, and implement a method to simply add an item to the list. No recursion needed.

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 16 8d

Want to read more? Browse other topics in C and C++ or view latest topics.