below is the code which implements a stack of size 10. Pointer are used to easily push and pop the data. please feel free to use the code. can be used in the gcc compiler. Please feel free to use any functionality. change the max value and you can change it to what ever size stack you want...
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define max 10
int pos;
int *pop(int *pnt)
{
int val=0;
if(pos==0)
{
printf("no elements to delete ");
}
else
{
printf(" deleted value is %d ",*pnt);
pnt--;
pos--;
}
return pnt;
}
int push(int *pntr)
{
int cntr;
int val;
if(pos==10)
{
printf("stack limit reached \n");
printf("pop out a member first\n");
}
else{
printf("enter the value to push \n");
scanf("%d",&val);
*pntr=val;
pos=pos+1;
printf("stack location %d \n",cntr);
}
return pos;
}
void ex()
{
exit(0);
}
void prstck(int cnt,int *pt)
{
int i;
for(i=pos-1;i>=0;i--)
{
printf(" stack elem at locn %d : %d \n", i,*pt);
pt--;
}
}
int main()
{
int st[10];
int sel=0;
int cnt;
int *stp; // stack pointer.
int *pppntr;
stp=st;
while(1)
{
printf("enter your selection \n");
printf("\n 1.push 2. pop 3. exit 4. display stack ");
scanf("%d",&sel);
switch(sel)
{
case 1 : stp++;
cnt=push(stp);
break;
case 2 : pppntr= pop(stp);
stp=pppntr;
break;
case 3 : ex();
break;
case 4 : prstck(cnt-1,stp);
break;
default : printf("no value entered \n");
break;
}
}
return 0;
}
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define max 10
int pos;
int *pop(int *pnt)
{
int val=0;
if(pos==0)
{
printf("no elements to delete ");
}
else
{
printf(" deleted value is %d ",*pnt);
pnt--;
pos--;
}
return pnt;
}
int push(int *pntr)
{
int cntr;
int val;
if(pos==10)
{
printf("stack limit reached \n");
printf("pop out a member first\n");
}
else{
printf("enter the value to push \n");
scanf("%d",&val);
*pntr=val;
pos=pos+1;
printf("stack location %d \n",cntr);
}
return pos;
}
void ex()
{
exit(0);
}
void prstck(int cnt,int *pt)
{
int i;
for(i=pos-1;i>=0;i--)
{
printf(" stack elem at locn %d : %d \n", i,*pt);
pt--;
}
}
int main()
{
int st[10];
int sel=0;
int cnt;
int *stp; // stack pointer.
int *pppntr;
stp=st;
while(1)
{
printf("enter your selection \n");
printf("\n 1.push 2. pop 3. exit 4. display stack ");
scanf("%d",&sel);
switch(sel)
{
case 1 : stp++;
cnt=push(stp);
break;
case 2 : pppntr= pop(stp);
stp=pppntr;
break;
case 3 : ex();
break;
case 4 : prstck(cnt-1,stp);
break;
default : printf("no value entered \n");
break;
}
}
return 0;
}
No comments:
Post a Comment