Stack ADT Implement Stack using Arrays in C Programming.
A stack is a linear data structure in which an element can be inserted or deleted only at one end of the list. A stack works on the principle of last in first out and is also known as a Last-In-First-Out (LIFO) list. Operations on a stack
- push
- Insert , a new object on top, stack
- Overflow Condition
- Pop
- Delete, top object, from the stack
- Underflow Condition
- A stack is an abstract data type (ADT) that supports
- Two main methods:
- push(element): Inserts object o onto top of stack
- Input: Object; Output: none
- pop(): Removes the top object of stack and returns it; if stack is empty an error occurs
- Input: none; Output: Object
- When stacks are represented as arrays, a variable named Top is used to point to the top element of the stack with MAX is the maximum size of the stack
- Initially the value of Top = -1 ( or 0) to indicate an empty
- Push an element onto the stack,
- Top is incremented by 1 and the element is pushed at that
- When Top reaches MAX-1 and an attempt is made to push a new element, then stack
- Pop (or remove) an element from the stack,
- the element on the top of the stack is assigned to a local variable and then Top is decremented by
- When the value of Top is equal to -1 and an attempt is made to pop an element, the stack underflows.
- Before inserting/deleting any element onto/from the stack, it is necessary to test the condition of overflow/underflow
- push(element): Inserts object o onto top of stack
#include <stdio.h> #include <conio.h> #include <stdlib.h> #define MAX 6
int menu()
{
int ch;
printf("\n -----------**********---------- \n");
printf("\n ....Stack operations using ARRAY.... ");
printf("\n -----------**********---------- \n");
printf("\n 1. Push ");
printf("\n 2. Pop "); printf("\n 3. Display"); printf("\n 4. Quit ");
printf("\n Enter your choice: "); scanf("%d", &ch);
return ch;
}
void display(int stack[],int *top)
{
int i;
if((*top) == 0)
{
printf("\n\nStack empty.."); return;
}
else
{
printf("\n\nElements in stack:"); for(i = (*top)-1; i >= 0 ; i--)
printf("\n%d", stack[i]);
}
}
void pop(int stack[],int *top)
{
if(*top == 0)
{
printf("\n\nStack Underflow.."); return;
}
else
printf("\n\npopped element is: %d ", stack[--(*top)]);
}
void push(int stack[],int *top)
{
int data;
if(*top == MAX)
{
printf("\n\nStack Overflow.."); return;
}
else
{
printf("\n\nEnter data: "); scanf("%d", &data);
stack[(*top)] = data;
*top = *top + 1;
printf("\n\nData Pushed into the stack");
}
}
void main()
{
int ch;
int stack[MAX]; int (*top) = 0;
}
do
{
ch = menu(); switch(ch)
{
case 1:
case 2:
case 3:
case 4:
}
getch();
} while(1);