Skip to content

Instantly share code, notes, and snippets.

@mbalayil
Created May 28, 2011 11:05
Show Gist options
  • Save mbalayil/996791 to your computer and use it in GitHub Desktop.
Save mbalayil/996791 to your computer and use it in GitHub Desktop.
Stack operations(basic) in C
/**
* A Stack is a last in, first out (LIFO) abstract data type and data
* structure.It is characterized by three fundamental operations: push,
* pop and stack top.
* PUSH : The push operation adds a new item to the top of the stack, or
* initializes the stack if it is empty, but if the stack is full and
* does not contain more space to accept the given item it is considered
* as an Overflow state (It means that the stack is overloaded or no more
* space for new item).
* POP : The pop operation removes an item from the top of the stack,
* but if the stack is empty then it goes into underflow state (It means
* no items are present in the stack to be removed).
* STACK TOP : The stack top operation gets the data from the top-most
* position and returns it to the user without deleting it. The same
* underflow state can also occur in stack top operation if stack is empty.
**/
#include<stdio.h>
#define MAX 50
int main()
{
int stack[MAX], top = -1, e;
int choice;
void PUSH(int *, int, int *);
void POP(int *, int *);
void DISPLAY_TOP(int *, int *);
while(1) {
printf("\nMenu\n1.PUSH\n2.POP\n3.DISPLAY STACK TOP\n4.EXIT\n");
printf("Type 1 to Push, 2 to Pop, 3 to display and 4 to Exit : \n");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter element to be pushed : \n");
scanf("%d", &e);
PUSH(stack, e, &top);
break;
case 2:
POP(stack, &top);
break;
case 3:
DISPLAY_TOP(stack, &top);
break;
case 4:
exit(0);
default:
printf("Invalid entry!!\n");
}
}
return 0;
}
void PUSH(int *stack, int item, int *top)
{
if((*top) == MAX - 1) {
printf("Stack Overflow!\n");
return;
} else {
stack[++(*top)] = item;
printf("%d inserted\n", item);
}
}
void POP(int *stack, int *top)
{
int item;
if((*top) == -1) {
printf("Stack underflow\n");
} else {
item = stack[(*top)];
printf("Popped item : %d\n", item);
(*top)--;
}
}
void DISPLAY_TOP(int *stack, int *top)
{
int i;
if(*top == -1)
printf("Stack underflow\n");
else {
printf("The stack contents are :\n");
for(i = 0; i <= (*top); i++)
printf("%d ",stack[i]);
printf("\nThe top of the stack : %d\n", stack[(*top)]);
printf("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment