Module 2-Stacks
Module 2-Stacks
Stacks
Introduction
• Stack is an important data structure which stores its elements in
an ordered manner.
• If TOP = NULL, then it indicates that the stack is empty and if TOP =
MAX -1, then the stack is full.
Push Operation
• The push operation is used to insert an element in to the stack.
• The new element is added at the topmost position of the stack.
• However, before inserting the value, we must first check if
TOP=MAX-1, because if this is the case then it means the stack is
full and no more insertions can further be done.
• If an attempt is made to insert a value in a stack that is already full,
an OVERFLOW message is printed.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D E F
0 1 2 3 4 TOP =5 6 7 8 9
Pop Operation
• The pop operation is used to delete the topmost element from the
stack.
• However, before deleting the value, we must first check if
TOP=NULL, because if this is the case then it means the stack is
empty so no more deletions can further be done.
• If an attempt is made to delete a value from a stack that is already
empty, an UNDERFLOW message is printed.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D
0 1 2 TOP = 3 4 5 6 7 8 9
Peek Operation
• Peek is an operation that returns the value of the topmost
element of the stack without deleting it from the stack.
• However, the peep operation first checks if the stack is empty or
contains some elements.
• If TOP = NULL, then an appropriate message is printed else the
value is returned.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
• Parentheses checker
• Recursion
• Tower of Hanoi
Infix Notation
• Infix, Postfix and Prefix notations are three different but
equivalent notations of writing algebraic expressions.
• While writing an arithmetic expression using infix notation, the
operator is placed between the operands. For example, A+B; here,
plus operator is placed between the two operands A and B.
• Although it is easy to write expressions using infix notation,
computers find it difficult to evaluate as they need a lot of
information to evaluate the expression.
• Information is needed about operator precedence, associativity
rules, and brackets which overrides these rules.
• So, computers work more efficiently with expressions written
using prefix and postfix notations.
Postfix Notation
• Postfix notation was given by Jan Łukasiewicz who was a Polish
logician, mathematician, and philosopher. His aim was to develop
a parenthesis-free prefix notation (also known as Polish notation)
and a postfix notation which is better known as Reverse Polish
Notation or RPN.
• In postfix notation, the operator is placed after the operands. For
example, if an expression is written as A+B in infix notation, the
same expression can be written as AB+ in postfix notation.
• The order of evaluation of a postfix expression is always from left
to right.
Postfix Notation
• The expression (A + B) * C is written as:
AB+C* in the postfix notation.
Ex. 934*8+4/-
Evaluation of an Infix Expression
STEP 1: Convert the infix expression into its equivalent postfix expression
Ex: A-(B/C+(D%E*F)/G)*H
#include<stdio.h> /* define function that is used to determine whether any symbol is operator or
#include<stdlib.h> /* for exit() */ This function returns 1 if symbol is opreator else return 0 */
#include<ctype.h> /* for isdigit(char ) */
#include<string.h>
int is_operator(char symbol)
#define SIZE 100
{
char stack[SIZE]; if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')
int top = -1; return 1;
else
/* define push operation */ return 0;
void push(char item) }
{ if(top >= SIZE-1) }
printf("\nStack Overflow.");
else /* define fucntion that is used to assign precendence to operator.
{ * In this fucntion we assume that higher integer value * means higher precende
top = top+1;
stack[top] = item; int precedence(char symbol)
} {
} if(symbol == '^')/* exponent operator, highest precedence*/
{
return 3;
/* define pop operation */ }
char pop() else if(symbol == '*' || symbol == '/')
{ char item ; {
if(top <0) return 2;
printf("stack under flow: invalid infix }
expression"); else if(symbol == '+' || symbol == '-') /* lowest precedence */
else {
return 1;
{ item = stack[top];
}
top = top-1; else
return(item); {
} return 0;
} }
}
Void InfixToPostfix(char infix_exp[], char postfix_exp[]) else if(item == ')') /* if current symbol is ')' then */
{ int i, j; { x = pop(); /* pop and keep popping until */
char item; while(x != '(') /* '(' encounterd */
char x; {
postfix_exp[j] = x;
strcat(infix_exp,")"); /* add ')' to infix expression*/
j++;
push('('); /* push '(' onto stack */ x = pop();
}
i=0; }
j=0; else
item=infix_exp[i]; {
/* if current symbol is neither operand not '(' nor ')' and
not operator */
while(item != '\0') /* run loop till end of infix expression */
printf("\nInvalid infix Expression.\n");
{ getchar();
if(item == '(') exit(1);
push(item); }
else if( isdigit(item) || isalpha(item)) i++;
{ postfix_exp[j] = item; /* add operand symbol to postfix expr */ item = infix_exp[i]; /* go to next symbol of infix expr
j++; } /* while loop ends here */
if(top>0)
}
{
else if(is_operator(item) == 1) /* means symbol is operator */ printf("\nInvalid infix Expression.\n”);
{ }
x=pop();
while(is_operator(x) == 1 && precedence(x)>= precedence(item)) postfix_exp[j] = '\0';
{ }
postfix_exp[j] = x; /* so pop all higher precendence operator*/
j++;
x = pop(); /* add them to postfix expression */
}
push(x);
push(item); /* push current operator symbol onto stack */
}
/* main function */
int main()
{
char infix[SIZE], postfix[SIZE]; /* declare infix string and postfix string */
return 0;
}
Evaluation of an Infix Expression
STEP 2: Evaluate the postfix expression
Ex. (A – B / C) * (A / K – L)
Evaluation of an Prefix Expression
Ex. +-27*8/48
Evaluation of Prefix Expression
• Step 1: Reverse the infix string. Note that while reversing the string
you must interchange left and right parenthesis.
Ex. (A – B / C) * (A / K – L)
Recursion
• Recursion is an implicit application of STACK ADT.
• A recursive function is a function that calls itself to solve a smaller
version of its task until a final call is made which does not require a
call to itself.
• Every recursive solution has two major cases: the base case in
which the problem is simple enough to be solved directly without
making any further calls to the same function.
• Recursive case, in which first the problem at hand is divided into
simpler subparts. Second the function calls itself but with subparts
of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
Types of Recursion
• Any recursive function can be characterized based on:
▪ whether the function calls itself directly or indirectly (direct or
indirect recursion).
▪ whether any operation is pending at each recursive call (tail-
recursive or not).
▪ the structure of the calling pattern (linear or tree-recursive).
Recursion
FIB(6) FIB(5)
FIB(2) FIB(1)
Pros and Cons of Recursion
Pros
• Recursive solutions often tend to be shorter and simpler than non-
recursive ones.
• Code is clearer and easier to use.
• Follows a divide and conquer technique to solve problems.
• In some (limited) instances, recursion may be more efficient.
Cons
• For some programmers and readers, recursion is a difficult
concept.
• Recursion is implemented using system stack. If the stack space on
the system is limited, recursion to a deeper level will be difficult to
implement.
• Aborting a recursive process in midstream is slow.
• Using a recursive function takes more memory and time to
execute as compared to its non-recursive counterpart.
• It is difficult to find bugs, particularly when using global variables.
Tower of Hanoi
Tower of Hanoi is one of the main applications of a recursion. It says, "if you can solve
n-1 cases, then you can easily solve the nth case"
A B C A B C
If there is only one ring, then simply move the ring from source to the destination
A B C
A B C A B C
A B C
A B C
A B C
A B C A B C
A B C
A B C A B C
C recursive function to solve tower of hanoi puzzle
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}