Basic stack operations in C
"A stack is a basic computer science data structure and can be defined in an abstract, implementation-free manner, or it can be generally defined as a linear list of items in which all additions and deletion are restricted to one end that is Top." - Wikipedia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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"); | |
} | |
} |
No comments:
Post a Comment