C Program to Perform Stack Operations Using Pointer.
·
Stack is a
linear data structure in which the operations are performed based on LIFO
principle.
·
In a Stack, adding and removing of elements are performed at single
position which is known as "top".
·
The insertion operation is performed using a function called push
and deletion operation is performed using a function called pop.
·
A Pointer is a variable whose value is the address of another
variable, that is direct address of the memory location.
---------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 50
int size;
struct stack
{
int arr[MAX];
int top;
}
void
init_stk(struct stack *st)
{
st->top = -1;
}
void push(struct
stack *st, int num)
{
if(st->top == size-1)
{
printf("\n Stack Overflow");
return;
}
st->top++;
st->arr[st->top] = num;
}
int pop(struct
stack *st)
{
int num;
if(st->top == -1)
{
printf("\n Stack
Underflow");
return NULL;
}
num = st->arr[st->top];
syt->top--;
return num;
}
void display(struct
stack *st)
{
int i;
for(i=st->top;i>=0;i--)
printf("\n %d",st->arr[i]);
}
int main( )
{
int element, opt, val;
struct stack ptr;
init_stk(&ptr);
printf("\n Enter Stack Size: ");
scanf("%d", &size);
while(1)
{
printf("\n\n Stack
Operations");
printf("\n1. Push");
printf("\n2.Pop");
printf("\n3.Display");
printf("\n4.Quit");
printf("\n");
printf("\n Enter Option :
");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\n Enter the element into
stack");
scanf("%d",
&val);
push(&ptr, val);
break;
case 2:
element = pop(&ptr);
printf("\n The element
popped from stack is %d",element);
break;
case 3:
printf("\n The current
stack elemengts are : ");
display(&ptr);
break;
case 4:
exit(0);
default:
printf("\n Enter correct
option! Try again.");
}
}
return(0);
}
Output
---------------------------------------------------------------------------------------------------------
Displays Stack
Operations
---------------------------------------------------------------------------------------------------------
Explanation
·
Declaring
the stack with MAX size
struct stack
{
int arr[MAX];
int top;
};
·
Initializing
the top location of stack to -1.
·
We
are passing the structure to the function using pointer so we can see struct
stack as data type in the function call.
void init_stk(struct stack
*st)
{
st->top = -1;
}
·
Access
the top element of stack using
st->top
·
Access
the 0th element of the stack array using
st->arr[0]
·
Access
the top element using
st->arr[st->top]
·
Perform
Push and Pop Operations.
EmoticonEmoticon