DATA STRUCTURES USING STACK
UNIT II
STACK
Stack Definition
It is an ordered group of elements.
A stack is a linear data structure where elements are stored in the LIFO (Last In First Out) principle
where the last element inserted would be the first element to be deleted.
To implement the Stack, it is required to maintain a pointer to the top of the Stack, which is the last
element to be inserted because we can access the elements only on the top of the Stack.
What are the Ways to implement Stack?
A stack can be implemented by means of Array, Structure, Pointer, and Linked List.
Stack can either be a fixed size one or it may have a dynamic size.
Here, we are going to implement stack using arrays, which makes it a fixed size Stack
Implementation
Array Representation of Stack
An array is used to store an ordered list of elements. Using an array for representation
of stack is one of the easy techniques to manage the data.
KLES BCA HUBBALLI 1
DATA STRUCTURES USING STACK
C
Applications of Stack
Balancing of symbols
Infix to Postfix /Prefix conversion
Redo-undo features at many places like editors, photoshop.
Forward and backward feature in web browsers
Used in many algorithms like Tower of Hanoi, tree traversals, stock span
problem, histogram problem.
Backtracking algorithm designing technique Some example are Knight-Tour
problem,N-Queen problem, find your way through maze and game like
chess
In Graph Algorithms
In Memory management any modern computer uses stack as the primary-
management for a running purpose.
String reversal is also an another application of stack. Here one by one each
character gets inserted into the stack. So the first character of string is on the
bottom of the stack and the last element of string is on the top of stack. After
Performing the pop operations on stack we get string in reverse order.
Stack Operations
1. Push(): Add an element to the top of a stack.
2. Pop(): Remove an element from the top of a stack.
3. Display (): To Traverse the Stack as it’s an array.
4. IsEmpty(): Check if the stack is empty.
5. IsFull(): Check if the stack is full.
6. Peek(): Get the value of the top element without removing it.
KLES BCA HUBBALLI 2
DATA STRUCTURES USING STACK
C
Implementation of Stack
All the Stack Operations are implemented with the help of Array and Top variable
with initialization to -1
Stack Operations can be performed randomly
Push Operation
The process of putting a new data element onto stack is known as a Push Operation.
Push operation involves a series of steps -
Step 1 - Checks if the stack is full.
Step 2 - If the stack is full, produces an error and exit.
Step 3 - If the stack is not full, increments top to point next empty space.
Step 4 - Adds data element to the stack location, where top is pointing.
Code implementation of Stack PUSH Operation
//Function to insert Data to Stack
void push ()
{
int value;
//Code to check stack overflow condition
if(TOP==MaxLimit-1)
{
printf("Stack is Full\n");
return;
}
printf("Enter Data To insert in Stack:");
KLES BCA HUBBALLI 3
DATA STRUCTURES USING STACK
C
scanf("%d", &value);
TOP++;
stack[TOP]=value;
printf("%d is Inserted at the %d Position\n", value,TOP);
}
Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation.
In an array implementation of pop() operation, the data element is not actually removed,
instead top is decremented to a lower position in the stack to point to the next value.
But in linked-list implementation, pop() actually removes data element and deallocates
memory space.
A Pop operation may involve the following steps –
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is pointing and
display top element.
Step 4 − Decreases the value of top by 1.
Code implementation of Stack POP Operation
//Function to Remove Data from Stack
void pop(){
//Code to check is Stack Empty Condition
if(TOP==-1){
printf("Stack Empty\n");
KLES BCA HUBBALLI 4
DATA STRUCTURES USING STACK
C
return;
}
printf("%d is Removed from the Stack at position %d\n", stack[TOP], TOP);
TOP--;
}
Display Operation
To Traverse the Stack elements as it’s an array
Code implementation of Stack display Operation
//Function to Traverse Stack
void display(){
//Code to check is Stack Empty Condition
if(TOP==-1){
printf("Stack Empty\n");
return;
}
printf("\nElements of Stack\n");
for(i=0;i<=TOP;i++){
printf("%d\n", stack[i]);
}
}
Stack Implementation Program
#include<stdio.h>
#include<stdlib.h>
int stack[100],choice,size,top=-1;
void push();
void pop();
void display();
//main function
int main()
{
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&size);
while(1)
{
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t [Link]\n\t [Link]\n\t [Link]\n\t [Link]");
printf("\n Enter the Choice:");
KLES BCA HUBBALLI 5
DATA STRUCTURES USING STACK
C
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:exit(1);
default:
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
return 0;
}
//function to push element to stack
void push()
{
int value;
if(top>=size-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&value);
top++;
stack[top]=value;
}
}
//function to remove element from stack
void pop()
{
if(top<=-1)
{
KLES BCA HUBBALLI 6
DATA STRUCTURES USING STACK
C
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
//function to display stack elements
void display()
{
int i;
if(top==-1){
printf("Stack Empty\n");
}
else{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
}
}
Expressions
Expressions in C programing language combine operands, operators, and
variables.
The evaluations of an expression in C happen according to the operator's
precedence.
Types of Expression
1. Infix Expression: An expression in which the operator is in between its two
operands.
Ex: A+B
2. Prefix Expression: An expression in which operator precedes its two operands
is called as prefix expression.
Ex: +AB
3. Postfix Expression: An expression in which operator follows its two operands
is called as postfix expression.
Ex: AB+
KLES BCA HUBBALLI 7
DATA STRUCTURES USING STACK
C
Stacks are used by compilers to help in the process of converting infix to postfix
arithmetic expressions and also evaluating arithmetic expressions.
Here, an expression represented by a String.
The expression can contain parentheses, Operators, Constants, Variables etc.
Expression Conversion
To evaluate expressions manually infix notation is helpful
But infix expressions are hard to parse in a computer program hence it will be
difficult to evaluate expressions using infix notation.
To reduce the complexity of expression evaluation of Prefix or Postfix
expressions are used in the computer programs.
Following are the expressions conversions will be discussed
1. Infix to postfix
2. Infix to prefix
Expressions conversion is implemented with any one of these two ways
1. Repetitive Substitution
2. Using stack
Infix to Postfix Conversion using Repetitive substitution
Example1
X$Y$Z–M+N+P/Q
X $ T1 - M + N + P / Q T1 =YZ$
T2 - M + N + P / Q T2 = XT1$
T2 - M + N + T3 T3 = PQ/
T4 + N + T3 T4 = T2M-
T5 + T3 T5= T4N+
T6 T6=T5T3+
Back Substitute the variables
T6
T5 T3 +
T4 N+ PQ/ +
T2 M – N+ PQ /+
X T1 $ M – N+ PQ /+
X Y Z $$ M – N+ PQ /+
KLES BCA HUBBALLI 8
DATA STRUCTURES USING STACK
C
Example2
Back substitute the values
Solve the Following infix Expression to Post fix Expression using Repetitive Substitution
1. (A+(B-C)*D)
2. X+(Y*Z)/A%B
3. M*(N/O)+P-Q
4. K+L-M*N+(O$P)*W/U/V*T+Q
Infix to Postfix Conversion using Stack Method
Algorithm to convert infix to postfix using stack
Step1 : Scan the infix expression from left to right
Step2 : If the scanned symbol is an operand then place directly into postfix
expression
Step 3: Else
2.1) If the scanned symbol is left parenthesis then push it into the stack.
2.2) If the scanned symbol is right parenthesis ‘)’ then pop all the items
from the stack and place in the postfix expression until left parenthesis is
found and discard both parenthesis.
KLES BCA HUBBALLI 9
DATA STRUCTURES USING STACK
C
2.3) If the scanned symbol is an operator and the precedence of the operator
is greater than the precedence of the operator on top of the stack then push it
into the stack.
2.4) Else pop all the operators from the stack which are greater than or equal
to the precedence than that of the scanned operator. After doing that push the
scanned operator on the stack. (if you encounter parenthesis while poping
then stop there and push the scanned operator onto the top of the stack.
Step 4 : Repeat step 2 and 3 until infix expression is scanned.
Step 5: Pop the items(operators ) from the stack and place in the postfix expression
until it is not empty.
Step 6 : print the postfix expression.
Note : No two operators of same priority can stay in the stack.
Example 1
Infix Expression : A+B
Scanned Postfix
Stack Description
Symbol expression
Since scanned symbol is an operand place it in postfix
A # A
expression
+ + A Scanned symbol is operator push into the stack
Since scanned symbol is an operand place it in postfix
B + AB
expression
Since the infix expression is scanned till last. The
# AB+ operators left in stack are poped and placed in postfix
expression
Postfix Expression : A+B
KLES BCA HUBBALLI 10
DATA STRUCTURES USING STACK
C
Infix Expression : A+B*C+D
Scanned Postfix
Stack Description
Symbol expression
Since scanned symbol is an operand place it in postfix
A # A
expression
+ + A Scanned symbol is operator push into the stack
Since scanned symbol is an operand place it in postfix
B + AB
expression
* +* AB Scanned symbol is * , whose precedence is more than
the operator on top of stack i.e +, push * into stack
C +* ABC Since scanned symbol is an operand place it in postfix
expression
Since scanned symbol is an operand place it in
C +* ABC
postfix expression
Since the scanned symbol + has precedence less than the
precedence of operator on top of stack. POP *+ from
+ + ABC*+
stack and place it in postfix expression and then push +
into the stack.
D + ABC*+D D is operand , add to postfix expression
Since the infix expression is scanned till last. The
# ABC*+D+ operators left in stack are poped and placed in postfix
expression
Post fix Expression : ABC*+D+
KLES BCA HUBBALLI 11
DATA STRUCTURES USING STACK
C
KLES BCA HUBBALLI 12
DATA STRUCTURES USING STACK
C
Infix to Prefix Conversion
Example1 :
Example 2:
KLES BCA HUBBALLI 13
DATA STRUCTURES USING STACK
C
Evaluation of Postfix Expression
Postfix expression is without parenthesis and can be evaluated as two operands and an operator
at a time; this becomes easier for the compiler and the computer to handle. The Postfix notation
is used to represent algebraic expressions. The expressions written in postfix form are evaluated
faster compared to infix notation as parenthesis are not required in postfix.
Steps to Evaluate Postfix Expression
Step 1: Create a stack that holds integer type data to store the operands of the given postfix
expression. Let it be st.
Step 2: Iterate over the string from left to right and do the following -
If the current element is an operand, push it into the stack.
Otherwise, if the current element is an operator (say /) do the following -
Pop an element from stack, let it be operand1.
Pop another element from stack, let it be operand2.
Compute the result of operand2 and operand1, and push it into the
stack. Note the order .i.e. operand2 / operand1 should not be changed
otherwise it will affect the final result in some cases.
Step 3: At last, stack will consist of a single element. i.e. the result after evaluating the postfix
expression.
KLES BCA HUBBALLI 14
DATA STRUCTURES USING STACK
C
Detailed Explanation of How to Evaluate a Postfix Expression Using Stack?
Let the the postfix expression be "10 22 + 8 / 6 * 5 +". Now, proceeding as per the algorithm -
1. Create a stack (say st).
2. Now since the first element is an operand, so we will push it in the stack .i.e. [Link](10). After
which stack looks like -
st
10
KLES BCA HUBBALLI 15
DATA STRUCTURES USING STACK
C
3. Now we traverse further in the postfix expression and found that the next element is again an
operand. So, we will push it into the stack, after which the stack will look like -
st
22
10
4. The next element of the expression is an operator (+ operator) so we will do the following -
1. Pop an element (say op1) from the stack. Here op1 = 22.
2. Pop another element (say op2) from the stack. Here op2 = 10.
3. Now, we will compute op2 + op1 which is 32, and push it into the stack. After this step stack will
look like -
st
32
5. On traversing further in the expression string, we found next element is an operand. So we will
push it into the stack. Upon doing this, the stack will look like -
St
8
32
6. The next element is the / operator, so we will do the following -
1. Pop an element (say op1) from the stack. Here op1 = 8.
2. Pop another element (say op2) from the stack. Here op2 = 32.
3. Now, we will compute op2 / op1 which is 4, and push it into the stack. After this step stack will look
like -
st
4
7. The next element is an operand, hence pushing it in the stack. After this step stack will look like -
st
6
4
8. The next element is the * operator, hence we need to perform the following steps -
1. Pop an element (say op1) from the stack. Here op1 = 6.
2. Pop another element (say op2) from the stack. Here op2 = 4.
3. Now, we will compute op2 * op1 which is 24, and push it into the stack. After this step stack will
look like -
st
24
9. The next operator is an operand, hence pushing it into the stack. Upon doing which stack will look
like -
st
5
24
KLES BCA HUBBALLI 16
DATA STRUCTURES USING STACK
C
10. The last element is the + operator. Hence it is required to do the following steps -
1. Pop an element (say op1) from the stack. Here op1 = 5.
2. Pop another element (say op2) from the stack. Here op2 = 24.
3. Now, we will compute op2 + op1 which is 29, and push it into the stack. After this step stack will
look like -
st
29
11. Now, we have traversed the given postfix expression, and hence as per the algorithm the only
element remaining in the stack i.e. 29 is the result we get on evaluating the postfix expression.
KLES BCA HUBBALLI 17