Created
June 14, 2012 07:56
-
-
Save tanayseven/2928876 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<iostream> | |
#include<malloc.h> | |
struct stack | |
{ | |
int info; | |
struct stack *next; | |
}; | |
//typedef struct stack *s; | |
//dont use type def!, typedef makes the function parameter local to that function. | |
//since the scope of that function is local, the value of sptr outside the function was NULL | |
void empty(struct stack * sptr) | |
{ | |
sptr->info = NULL; | |
sptr->next = NULL; | |
} | |
void push(struct stack * sptr ,int p) | |
{ | |
struct stack * s2; | |
s2=(struct stack *)malloc(sizeof(struct stack)); | |
if(s2==NULL) | |
{ | |
printf("no memory"); | |
// exit(1); //dont use exit | |
return; //use return insted | |
} | |
else | |
{ | |
s2->info=p; | |
s2->next=sptr; | |
sptr=s2; | |
} | |
} | |
int pop(struct stack * sptr) //pop should return the popped value | |
{ | |
struct stack * s2=sptr; | |
int px; | |
if(sptr==NULL) | |
{ | |
// exit(1); //dont use exit | |
return NULL; //use return insted | |
} | |
else | |
{ | |
px=sptr->info; | |
sptr=sptr->next; | |
free(sptr); | |
return px; //you were not returning | |
} | |
} | |
void disp(struct stack * sptr) | |
{ | |
printf("\n address: %p\n",sptr); | |
struct stack * temp=sptr; | |
printf("the elements in stack are:\n"); | |
while(sptr->next!=NULL) | |
{ | |
printf("%d\n",sptr->info); | |
sptr=sptr->next; | |
} | |
sptr=temp; | |
} | |
void main() | |
{ | |
int c,i; | |
struct stack s1; | |
empty(&s1); | |
printf("\n address: %p\n",&s1); | |
do{ | |
printf("enter operation (0-exit, 1-push 2-pop, 3-display):-"); | |
scanf("%d",&c); | |
switch(c) | |
{ | |
case 1: printf("Pushing: enter data:-"); | |
scanf("%d",&i); | |
printf("\n address: %p\n",&s1); | |
push(&s1,i); | |
printf("\n address: %p\n",&s1); | |
break; | |
case 2:printf("Popping: %d", pop(&s1)); | |
printf("\n address: %p\n",&s1); | |
break; | |
case 3:disp(&s1); | |
printf("\n address: %p\n",&s1); | |
break; | |
} | |
}while(c!=NULL); //you had put s1 == NULL and s1 was always NULL, so it was executing only once! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment