R23_DS_Unit III-1
R23_DS_Unit III-1
Stacks: Introduction to stacks: properties and operations, implementing stacks using arrays
and linked lists, Applications of stacks in expression evaluation, backtracking, reversing
list etc.
Introduction to Stacks:
Stack is a linear data structure in which element insertion and deletion can be done at one end
called top of the stack.
The top element of the stack is the last element added to the stack.
Also the top element of the stack is the first element to be removed from the stack.
So it works on the principle called Last in First out (LIFO) mechanism. Sometimes it is also
called as First in Last out (FILO) mechanism.
Hence, this stack is also called as LIFO or FILO list.
There are many real life examples of stack. For example plates stacked over one another in
canteen. CDs are placed in its stand. Shuttle cocks placed in barrel.
Operations: There are two basic operations can be performed over stacks, which are given as
1. PUSH
2. POP
3. PEEK
1. PUSH: This operation is used to insert an element into the stack. At the time of insertion of
element first check stack is full or not. If the stack is full then it generates an error message
that “stacks overflows”.
2. POP: This operation is used to delete an element from the stack. At the time of deletion of
element first check stack is empty or not. If the stack is empty then it generates an error
message “stack underflows”.
3. PEEK: This operation is used to get the top element of the stack without removing it. This
can be useful in situations where we need to check the top element without altering the state
of the stack.
Representation or Implementation:
A stack is implemented using two representations like
1. Array Implementation
2. Linked list Implementation
Array Implementation:
In this implementation, stack elements are stored in an array.
Every stack is associated with a variable called Top which indicates index of array to insert an
element or delete an element of stack.
There is another variable called Max which is used to store maximum number of elements
that the stack can hold.
Generally we initialize Top with -1. So, the condition Top==-1 indicates that stack is empty
and Top will be incremented by 1 for every PUSH operation and then the condition
Top==Max-1 indicates that stack is full.
Algorithm of PUSH:
1. Check if stack is full or not
2. If it is full then print an error message that stack overflows and exit
3. If it is not full then increment Top and insert element at Top index.
Example: