Skip to content

Instantly share code, notes, and snippets.

@tanayseven
Created June 14, 2012 08:03
Show Gist options
  • Save tanayseven/2928904 to your computer and use it in GitHub Desktop.
Save tanayseven/2928904 to your computer and use it in GitHub Desktop.
#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;
}
struct stack * newNode()
{
return (struct stack *)malloc(sizeof(struct stack));
}
void push(struct stack * sptr ,int p)
{
struct stack * s2;
s2=newNode();
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