Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

STACK IMPLEMENTATION

Presented by: Arpit Singh


Class: B. Sc. Year-2nd Sem-3rd
Roll No: 190014025020
INTRODUCTION
Stack is an important data structure which stores its
elements in an ordered manner. A stack is a linear data
structure in which the elements are added and
removed only from one end, which is called the TOP. A
stack is called a LIFO (Last-In-First-Out) data
structure, as the element that was inserted last is the
first one to be taken out.
ARRAY REPRESENTATION OF
STACK
In the computer’s memory, stacks can be represented
as a linear array.
Every stack has a variable called TOP associated with
it, which is used to store the address of the topmost
element of the stack. It is this position where the
element will be added to or deleted from.
There is another variable called MAX, which is used
to store the maximum number of elements that the
stack can hold.
If TOP = NULL, then it indicates that the stack is
empty and if TOP = MAX–1, then the stack is full.
ARRAY REPRESENTATION OF
STACK

5 10 15 20 25
0 1 2 3 4 5 6 7 8 9

Here, TOP = 4
And, MAX = 10
OPERATIONS ON A STACK
A stack supports three basic operatioins:
1. Push: The push operation adds an element to the top
of the stack
2. Pop: The pop operation removes the element from the
top of the stack.
3. Peek: The peek operation returns the value of the
topmost element of the stack.
STACK OVERFLOW AND STACK
UNDERFLOW

Stack Overflow: When we try to push an


element on the stack which is already full,
we get an error which is known as “Stack
Overflow”.
Stack Underflow: When we try to pop an
element from an empty stack, we get an
error which is known as “Stack Underflow”.
IMPLEMENTATION USING C++
We can easily implement stack using arrays in
C++ programming language. We will see how
we can implement each and every of the three
operations.

1. Push Operation: Suppose we want to push


an integer ‘val’ in a stack. The code for this
will be as follows:
Here, stack is an array which is used to implement
the stack and n is the maximum number of
elements in the stack, i.e., size of the array stack.
2. Pop Operation: Similarly, we can implement
pop() function in the following way:
3. Peek Operation: We can implement
peek() function in the following way:
THANK YOU

You might also like