c - First time creating Stack.One line is printing twice.Why? -


i have updated previous code said there 1 last problem. don't know why there line keeps on printing twice when run code.

and line is:

printf("\nenter values of x:"); 

and code is:

   #include <stdio.h> #include<stdlib.h> typedef struct node{   int a;  struct node* next; }node;  node* create(node* s) {   s=null;   printf("\n empty stack created\n");   return s; }  node* insert(node* s,int x) {   if (s==null)   {   s=malloc(sizeof(node));   s->a=x;   s->next=null;   }    else   {     node* temp=malloc(sizeof(node));     temp->a=x;     temp->next=s;     s=temp;   }   return s; } node* print(node* s) {   while(s!=null)   {     printf("%d",s->a);     s=s->next;   }   return s; } node* delete(node* s) {   node* s1;   if(s==null)   {   printf("trying delete empty list");   }   else   {    s1=s->next;    printf("element deleted %d",s->a);    s->next=null;    free(s);    }   return s1; } node* delete(node*s); node* insert(node*s,int x); node* create(node* s); node* print(node* s); int main() { node* top; top=create(top); char x; int val; while(1) {    printf("\nenter values of x:");   scanf("%c",&x);   switch(x)   {   case 'i':   {     printf("\nplease enter value inserted\n");     scanf("%d",&val);     top=insert(top,val);     break;   }   case 'd':   {     delete(top);     break;   }   case 'p':   {     top=print(top);   }   case 'e':   {       return 0;   } } } } 

in typedef declaration

typedef struct {   int a;  struct node* next; }node; 

there declared 2 types. first 1 unnamed structure type gets typedef name node. second 1 incomplete struct node declared within unnamed structure.

as result example in statement in function insert

temp->next=s; 

there attempt assign pointer of type node s pointer of type struct node temp->next , there no implicit conversion 1 pointer another.

you should rewrite typedef following way

typedef struct node {   int a;  struct node* next; }node; 

in case names struct node , node refer same entity.

pay attention function

node* create(node* s) {   s=null;   printf("\n empty stack created");   return s; } 

does not make sense, in fact parameter redundant. can write

node* create( void ) {   printf("\n empty stack created");   return null; } 

or

void create(node **s) {   *s = null;   printf("\n empty stack created"); } 

also function

node* delete(node* s) {   node* s1;   if(s==null)   {   printf("trying delete empty list");   }   else   {    s1=s->next;    printf("element deleted %d",s->a);    s->next=null;    free(s);    }   return s1; } 

has undefined behavior because return uninitialized pointer s1 when s equal null.

and have use return value of function delete call

delete(top); 

is incorrect because original pointer top not changed.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -