Write a C program using pointers to implement a stack
with all the operations
#include
#include
#include
#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("\nStack
overflow(i.e., stack full).");
return;
}
st->top++;
st->arr[st->top] = num;
}
int pop(struct stack *st)
{
int num;
if (st->top == -1)
{
printf("\nStack
underflow(i.e., stack empty).");
return NULL;
}
num = st->arr[st->top];
st->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("\nEnter Stack Size
:");
scanf("%d", &size);
while (1)
{
printf("\n\ntStack
Primitive operations");
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.DISPLAY");
printf("\n4.QUIT");
printf("\n");
printf("\nEnter
your option : ");
scanf("%d",
&opt);
switch (opt)
{
case 1:
printf("\nEnter the element into stack:");
scanf("%d", &val);
push(&ptr, val);
break;
case 2:
element = pop(&ptr);
printf("\nThe element popped from stack is : %d", element);
break;
case 3:
printf("\nThe current stack elements are:");
display(&ptr);
break;
case 4:
exit(0);
default:
printf("\nEnter correct option!Try again.");
}
}
return (0);
}
C Program to implement Stack Operations Using Stack
#include
#include
#include
#define size 5
struct stack
{
int s[size];
int top;
}
st;
int stfull()
{
if (st.top >= size - 1)
return 1;
else
return 0;
}
void push(int item)
{
st.top++;
st.s[st.top] = item;
}
int stempty()
{
if (st.top == -1)
return 1;
else
return 0;
}
int pop()
{
int item;
item = st.s[st.top];
st.top--;
return (item);
}
void display()
{
int i;
if (stempty())
printf("\nStack
Is Empty!");
else {
for (i =
st.top; i >= 0; i--)
printf("\n%d", st.s[i]);
}
}
int main()
{
int item, choice;
char ans;
st.top = -1;
printf("\n\tImplementation Of
Stack");
do
{
printf("\nMain
Menu");
printf("\n1.Push
\n2.Pop \n3.Display \n4.exit");
printf("\nEnter
Your Choice");
scanf("%d",
&choice);
switch
(choice)
{
case 1:
printf("\nEnter The item to be pushed");
scanf("%d", &item);
if (stfull())
printf("\nStack
is Full!");
else
push(item);
break;
case 2:
if (stempty())
printf("\nEmpty
stack!Underflow !!");
else {
item
= pop();
printf("\nThe
popped element is %d", item);
}
break;
case 3:
display();
break;
case 4:
exit(0);
}
printf("\nDo
You want To Continue?");
ans =
getche();
} while (ans == 'Y' || ans == 'y');
return 0;
}
No comments:
Post a Comment