Data Structure
Data Structure
TECHNOLOGY
B. TECH DIVISION
CA-I EXAMINATION
Semester - III
Department - CSE
STACK AND IT’S OPERATION
WHAT IS STACK ?
A stack is a fundamental data structure used in
computer science. It operates on a Last In, First Out
(LIFO) principle, meaning that the last element
added to the stack is the first one to be removed.
This characteristic makes stacks useful for various
applications, such as function call management,
expression evaluation, and backtracking algorithms.
OPERATIONS ON A STACK :
Push:
>>> Definition Adds an element to the top of the stack. -
>>>Example: If the stack is [] (empty) and we push 5, the stack becomes [5]. Pushing 10 onto the stack [5]
results in [5, 10]
Pop :
>>>Definition : Removes and returns the top element of the stack.
>>>Example : If the stack is [5, 10], popping the stack removes 10, leaving the stack as [5], and the value 10
is returned.
Peek :
>>>Definition : Returns the top element of the stack without removing it.
>>> Example : For the stack [5, 10], peeking returns 10 without modifying the stack.
isEmpty :
>>>Definition : Checks whether the stack is empty.
>>>Example: For an empty stack [], isEmpty() returns true. For a non-empty stack [5], it returns false.
Size :
>>>Definition : Returns the number of elements in the stack.
>>>Example : For the stack [5, 10], size() returns 2.
IMPLEMENTS STACKS USING ARRAYS IN C:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
int top = -1, inp_array[SIZE];
void push();
void pop();
void show();
int main()
{
int choice;
while (1)
{
printf("\nPerform operations on the stack:");
printf("\n1.Push the element\n2.Pop the
element\n3.Show\n4.End");
printf("\n\nEnter the choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
exit(0);
default:
printf("\nInvalid choice!!");
}
}
}
void push()
{
int x;
if (top == SIZE - 1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter the element to be added onto the stack: ");
scanf("%d", &x);
top = top + 1;
inp_array[top] = x;
}
}
void pop()
{
if (top == -1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nPopped element: %d", inp_array[top]);
top = top - 1;
}
}
void show()
{
if (top == -1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nElements present in the stack: \n");
for (int i = top; i >= 0; --i)
printf("%d\n", inp_array[i]);
}
}
This program presents the
user with four options:
Output
Perform operations on the stack:
1.Push the element
2.Pop the element
3.Show
4.End
Output
Perform operations on the stack:
1.Push the element
2.Pop the element
3.Show
4.End
Output
Perform operations on the stack:
1.Push the element
2.Pop the element
3.Show
4.End
Output
Perform operations on the stack:
1.Push the element
2.Pop the element
3.Show
4.End