Stack implementation can be done in three ways
1> using arrays
2> using linked lists
3> using 2 queues
let's see the program for stack implementation with the help of linked list
#include<stdio.h>
struct node1{
int top, size;
int *sptr;
};
typedef struct node1 stack;
void push(stack *s,int value )
{
if(s->top!=s->size-1)
{
s->top ++;
s->sptr[s->top] = value;
}
else
{
printf("stack is already full so can't enter %d \n",value);
}
}
int pop(stack *s)
{
if (isempty(s))
{
printf("stack is already empty ");
return 0;
}
else
{
int x= s->sptr[s->top];
s->top = s->top -1 ;
return x;
}
}
int isempty(stack *s)
{
if(s->top==-1)
{
return 1;
}
else
return 0;
}
void print(stack s1)
{
int i ;
for ( i=0;i<=(s1.top);i++)
{
printf("%d\n",s1.sptr[i]) ;
}
}
void main()
{
stack s1;
printf("enter the size of stack");
scanf("%d",&s1.size);
s1.sptr=(int*)malloc(sizeof(int)*(s1.size));
s1.top=-1;
int m=pop(&s1);
printf("%dabc\n",m);
push(&s1,8);
push(&s1,23);
push(&s1,43);
push(&s1,21);
push(&s1,54);
print(s1);
m=pop(&s1);
printf("the value after pop is %d",m);
}
1> using arrays
2> using linked lists
3> using 2 queues
let's see the program for stack implementation with the help of linked list
#include<stdio.h>
struct node1{
int top, size;
int *sptr;
};
typedef struct node1 stack;
void push(stack *s,int value )
{
if(s->top!=s->size-1)
{
s->top ++;
s->sptr[s->top] = value;
}
else
{
printf("stack is already full so can't enter %d \n",value);
}
}
int pop(stack *s)
{
if (isempty(s))
{
printf("stack is already empty ");
return 0;
}
else
{
int x= s->sptr[s->top];
s->top = s->top -1 ;
return x;
}
}
int isempty(stack *s)
{
if(s->top==-1)
{
return 1;
}
else
return 0;
}
void print(stack s1)
{
int i ;
for ( i=0;i<=(s1.top);i++)
{
printf("%d\n",s1.sptr[i]) ;
}
}
void main()
{
stack s1;
printf("enter the size of stack");
scanf("%d",&s1.size);
s1.sptr=(int*)malloc(sizeof(int)*(s1.size));
s1.top=-1;
int m=pop(&s1);
printf("%dabc\n",m);
push(&s1,8);
push(&s1,23);
push(&s1,43);
push(&s1,21);
push(&s1,54);
print(s1);
m=pop(&s1);
printf("the value after pop is %d",m);
}
No comments:
Post a Comment