THE STACK
Def:
A stack is a special type of data structure, where elements
are inserted from one end and elements are deleted from the
same end.
The position from where elements are inserted and from
where elements are deleted is called top of the stack.
Stack is also called as Last In First Out(LIFO) data
structures.
Stack operations:
1. Push( Inserting an element on top of the stack)
2. Pop(Deleting an element from top of the stack)
3. Display(Display contents of stack).
Push Operation:
Inserting an element into the stack is called push
operation.
Only one item is inserted at a time & item has to be
inserted only from top of the stack.
Empty Stack Stack With elements
4 4
3 3 top
2 2
1 1
0 0
top = -1
12
05
15
24
Inserting an element to stack : (push operation )
4 4 4 4
3 3 3 3
2 2 2 top 2
1 2 top 1 1
0 top 0 0 0
top=-1
4 top 4
top 3 3
2 2
1 1
0 0
* If we try to insert one more element it results in a “ overflow of
Stack”
10
40
30
20
10
20
10
30
20
10
50
40
30
20
10
// C function for Push Operation.
void push() //function ---1
{
/* check for overflow of stack */
if (top == stack_size-1)
{
printf(“ stack overflow);
return;
}
top = top+1;
S[top] = item;
}
Pop operation:
Deleting an element from the stack is called
“ Pop operation”.
Only one item is deleted from the stack
and the item has to be deleted only from top of the stack.
Deleting an element to stack : (pop operation )
top 4 4 4 4
3 top 3 3 3
2 2 top 2 2
1 2 1 top 1
0 0 0 0
4 4
3 3
2 2
1 1
top 0 0
top = -1
* If we try to delete one more element it results in a “ underflow of Stack”
10
40
30
20
10
20
10
30
20
10
50
40
30
20
10
// C function to delete an item from stack.
int pop() //function----2
{
int item_deleted;
if (top == -1)
{
printf(“ Stack Underflow “);
return 0;
}
item_deleted = S[top--];
return item_deleted;
}
Display stack items:
The contents of the stack are displayed from the bottom
to top.
// C function to display the contents of stack
Void display() //function----3
{
int i;
if ( top == -1 )
{ Printf(“ stack is empty”);}
for( i=0; i<=top; i++ )
{
printf(“%d”, S[i]);
}
}
Void main()
{
int item;
int item_deleted;
int choice;
top = -1;
for( ; ; )
{
printf(“1. push, 2. pop, 3. Display, 4. Exit”);
printf(“enter the choice”);
Scanf(“%d”,&choice);
Switch(choice)
{
Case 1:
printf(“ Enter the item to be inserted”);
Scanf(“%d”, &item);
push();
break;
Case 2:
item_deleted = pop();
if (item_deleted == 0)
printf(“stack is empty”);
else
printf(“Item deleted= %d”, item_deleted);
break;
Case 3:
display();
break;
default:
exit(0);
}
}
}
Applications of stack:
The various applications in which stacks are used are :
1.Conversion of expressions
2.Evaluation of expressions
3.Recursion
Conversion of expressions
The sequence of operators and operands that reduces to a
single value after evaluation is called an expression.
There are three different types of expressions:
Prefix Expression:
Postfix expression:
Infix expression:
Infix expression:
In an expression, if an operator is in the b/w two
operands, the expression is called an infix expression.
Ex: a+b, (a-b), (a+b*c-(d*f))
Postfix expression:
In an expression, if an operator follows the two
operands ( operator comes after the two operands ) , the expression
is called “postfix expression”. It is also called as
“Suffixexpression”.
Ex: ab+, ab-, (a+b*c) ab*c+
Prefix Expression:
In an expression, if an operator precede the two
operands(i.e., operator comes before the two operands), the
expression is called “Prefix Expression”.
Ex: +ab, -ab….
Precedence and Associativity of the operator :
While evaluating the expressions, some expressions are given
precedence over other expression and are evaluated first and some
are evaluated later.
“ The rules that determines the order in which the
different operators are evaluated are called precedence rules Or
precedence operators”.
The below table shows arithmetic operators along
with priority values,
Description Operator Priority
Exponentiation $ 6
Multiplication * 4
Division / 4
Mod % 4
Addition + 2
Substraction - 2
Associativity of the operator :
“ The order in which the operators with same
precedence are evaluated in an expression is called associativity of
the operator”.
In such cases the precedence rules are considered with
associativity.
The associativity can be classified into two types,
left to right associative ( left associative)
right to left associative (right associative).
left to right associative ( left associative) :
In an expression, if there are two or more operators
having the same priority and are evaluated from left to right , then
the operators are called left associative operators.
Right to left associative (right associative) :
In an expression, if there are two or more operators
having the same priority and are evaluated from right to left , then
the operators are called right associative operators.
The below table shows arithmetic operators along with
priority values and there associativity.
Description Operator Priority Associativity
Exponentiation $ 6 Right to left
Multiplication * 4 Left to right
Division / 4 Left to right
Mod % 4 Left to right
Addition + 2 Left to right
Subtraction - 2 Left to right
By substituting the values of T5,T4,T3,T2,T1 we get postfix
expression,
T5T3+ T5 = T4N+ and T3 = PQ/
T4N +PQ/+ T4 = T2M-
T2M-N+PQ/+ T2 = XT1^
XT1^M-N+PQ/+ T1 = YZ^
XYZ^^M-N+PQ/+
X ^ Y ^ Z-M +N+P/Q = XYZ^^M-N+PQ/+
To write a program by using stack data structure,
Let us use two precedence function F and G. The
function F contains the precedence values of symbols on top of
the stack and function G contains the precedence values of
symbols in the input string.
Shown in below table,( infix to postfix )
SymbolsStack precedence
“F”
Input precedence
“G”
Associativity
+ , - 2 1 Left
* , / 4 3 Left
$ or ^ 5 6 Right
Operands 8 7 Left
( 0 9 Left
) - 0 -
# -1 -
General procedure to convert from infix to postfix form :
Step 1 :
initialize top and stack of top
top = -1
s[++top] = ‘#’
j = 0
Step 2 :
As long as the precedence value of the symbol on top of
the stack is greater than the precedence value of the current input
symbol, pop an item from the stack and place it in the postfix
expression.
while ( F(s[top]) > G(symbol) )
{
postfix[ j++ ] = s[ top-- ]
}
Step 3 :
Once the condition in while loop is failed, if the
precedence of the symbol on top of the stack is not equal to the
precedence value of the current input symbol, push the current
symbol on to the stack. Otherwise , delete an item from the stack
but do not place in the postfix expression.
if ( F(s[top]) != G(symbol) )
s[++top] = symbol
else
top--;
Step 4 :
After the complete execution of step 2 and step 3, pop
remaining symbols from stack to postfix expression.
while ( s[top] != ‘#’ )
postfix[j++] = s[top--]
* complete trace of the algorithm :
( A + ( B – C ) * D )
Stack S[top]Symbol F(s[top]) > G(symbol) Postfix
# #
# # ( ( -1 > 9 ) push (
#( ( A ( 0 > 7 ) push A
#(A
#(
A
(
+ ( 8 > 1 ) pop A
( 0 > 1 ) push +
A
#(+ + ( ( 2 > 9 ) push (A
#(+( ( B ( 0 > 7 ) push B A
#(+(B
#(+(
B
(
- ( 8 > 1 ) pop B
( 0 > 1 ) push -
AB
#(+(- - C ( 2 > 7 ) push CAB
#(+(-C
#(+(-
#(+(
C
-
(
) ( 8 > 0 ) pop C
( 2 > 0 ) pop –
( 0 = 0 ) pop (
Don’t place in postfix expr
ABC
ABC-
* complete trace of the algorithm :
( A + ( B – C ) * D )
Stack S[top]Symbol F(s[top]) > G(symbol) Postfix
#(+ + * ( 2 > 3 ) push *ABC-
#(+* * D (4 > 7) push D ABC-
#(+*D
#(+*
#(+
#(
D
*
+
(
) ( 8 > 0 ) pop D
( 4 > 0 ) pop *
( 2 > 0 ) pop +
( 0 = 0 ) pop (
Don’t place in postfix expr
ABC-D
ABC-D*
ABC-D*+
# # ABC-D*+
/* C function for stack precedence
int F (char symbol) function 1
{
Switch (symbol)
{
Case ‘+’ :
Case ‘-‘ : return 2;
Case ‘*’ :
Case ‘/’ : return 4;
Case ‘^’ :
Case ‘$’ : return 5;
Case ‘(‘ : return 0;
Case ‘#’: return -1;
default : return 8;
}
}
/* C function for input precedence
int G (char symbol) function 2
{
Switch (symbol)
{
Case ‘+’ :
Case ‘-’ : return 1;
Case ‘*’ :
Case ‘/’ : return 3;
Case ‘^’ :
Case ‘$’ : return 6;
Case ‘(’ : return 9;
Case ‘)’ : return 0;
default : return 7;
}
}
/* C function to convert from infix into postfix expression.
void infix_postfix(char infix[], char postfix[])
{
//function 3
int top; int j; int I;
char s[30]; char symbol;
top=-1; Step : 1
S[++top]= ‘#’;
j=0;
for(i=0; i<strlen(infix); i++)
{
Symbol=infix[i];
/* if stack precedence greater , remove symbol from
stack and place into postfix. */
// C program to convert an infix expression to postfix expression
# include < stdio.h>
# include < string.h >
/* include function 1, function 2, function 3. */
void main ()
{
char infix[20];
char postfix[20];
printf (“ Enter the valid infix expression”);
scanf (“ %s ”, infix );
infix_postfix ( infix, postfix);
printf (“ The postfix expression is “ );
printf (“%s”,postfix);
}
To write a program by using stack data structure,
Let us use two precedence function F and G. The function F
contains the precedence values of symbols on top of the stack and
function G contains the precedence values of symbols in the input
string.
Shown in below table,( infix to prefix )
SymbolsStack precedence
“F”
Input precedence
“G”
Associativity
+ , - 1 2 Left
* , / 3 4 Left
$ or ^ 6 5 Right
Operands 8 7 Left
( - 0 Left
) 0 9 -
# -1 - -
General procedure to convert from infix to prefix form :
Step 1 :
initialize top and stack of top
top = -1
s[++top] = ‘#’
j = 0.( reverse the infix expression )
Step 2 :
As long as the precedence value of the symbol on top of the stack
is greater than the precedence value of the current input symbol, pop an
item from the stack and place it in the postfix expression.
while ( F(s[top]) > G(symbol) )
{
postfix[ j++ ] = s[ top-- ]
}
Step 3 :
Once the condition in while loop is failed, if the precedence of
the symbol on top of the stack is not equal to the precedence value of the
current input symbol, push the current symbol on to the stack. Otherwise
, delete an item from the stack but do not place in the postfix expression.
if ( F(s[top]) != G(symbol) )
s[++top] = symbol
else
top--;
Step 4 :
After the execution of step 2 and step 3, pop remaining symbols
from stack to postfix expression.
while ( s[top] != ‘#’ )
postfix[j++] = s[top--]
reverse the resultant expression
* complete trace of the algorithm :
( A + ( B – C ))= ) ) C – B ( + A (
i.e.,CB-A+ = +A-BC
Stack S[top]Symbol F(s[top]) > G(symbol) Postfix
# # ) -1 > 9 push ‘)’
#) ) ) 0 > 9 push ‘)’
#)) ) C 0 > 7 push ‘C’
#))C
#))
C
)
- 8 > 2 pop ‘C’
0 > 2 push ‘-’
C
#))- - B 1 > 7 push ‘B’ C
#))-B
#))-
#))
B
-
)
( 8 > 0 pop ‘B’
1 > 0 pop ‘-’
0 > 0 pop ‘)’
CB
CB-
#) ) + 0 > 2 push ‘+’ CB-
#)+ + A 1 > 7 push ‘+’ CB-
#)+A
#)+
#)
A
+
)
( 8 > 0 pop ‘A’
1 > 0 pop ‘+’
0 > 0 pop ‘)’
CB-A
CB-A+
/* C function for stack precedence
int F (char symbol) function 1
{
Switch (symbol)
{
Case ‘+’ :
Case ‘-‘ : return 1;
Case ‘*’ :
Case ‘/’ : return 3;
Case ‘^’ :
Case ‘$’ : return 6;
Case ‘)‘ : return 0;
Case ‘#’: return -1;
default : return 8;
}
}
/* C function for input precedence
int G (char symbol) function 2
{
Switch (symbol)
{
Case ‘+’ :
Case ‘-’ : return 2;
Case ‘*’ :
Case ‘/’ : return 4;
Case ‘^’ :
Case ‘$’ : return 5;
Case ‘(’ : return 0;
Case ‘)’ : return 9;
default : return 7;
}
}
/* C function to convert from infix into prefix expression.
void infix_prefix(char infix[], char prefix[])
{ // function 3
int top; int j; int I;
char s[30]; char symbol;
top=-1; Step : 1
S[++top]= ‘#’;
j=0;
strrev ( infix );
for(i=0; I < strlen (infix); i++)
{
Symbol=infix[i];
/* if stack precedence greater , remove symbol from
stack and place into prefix. */
// C program to convert an infix expression to prefix expression
# include < stdio.h>
# include < string.h >
/* include function 1, function 2, function 3. */
void main ()
{
char infix[20];
char prefix[20];
printf (“ Enter the valid infix expression”);
scanf (“ %s ”, infix );
infix_prefix ( infix, prefix);
printf (“ The prefix expression is “ );
printf (“%s”, prefix);
}
Evaluation of postfix expression :
Algorithm:
Step 1 : Scan the symbol from left to right.
Step 2: If the scanned symbol is an operand, push it on
to the stack.
Step 3: If the scanned symbol is an operator, pop two
elements from the stack
The first popped element is operand 2 and the
second popped element is operand1
Op2 = s[top--];
Op1 = s[top--];
Step 4: perform the indicated operation.
res = op1 op op2.
Step 5: push the result on to the stack.
Step 6: Repeat the above procedure till the end of the
i/p is encountered.
Ex: Evaluate the following postfix expression.
ABC-D*+E$F+ infix((A+(B-C)*D)$E+F)
with the values,
A=6, B=3, C=2, D=5, E=1, F=7.
Solution:
After substituting the values
// c program to evaluate the postfix expression:
#include < stdio.h >
#include < math.h >
#include < string.h >
double compute(char symbol, double op1, double op2)
{
switch ( symbol)
{
Case ‘+’ : return op1+op2;
Case ‘-’ : return op1-op2;
Case ‘*’ : return op1*op2;
Case ‘/’ : return op1/op2;
Case ‘$’:
Case ‘^’: return pow(op1,op2);
} }
void main()
{
double s[20] , res , op1 , op2 ;
int top, i ;
char postfix[20] , symbol ;
top = -1;
Printf(“ enter the postfix expression”);
Scanf(“%s”, postfix);
for ( i=0; i<strlen(postfix); i++ )
{
Symbol = postfix[i];
if ( isdigit(symbol))
S[++top]= symbol ;
else
{
op2 = s[top--];
op1 = s[top--];
res = compute(symbol, op1,op2);
S[++top] = res;
}
}
res = s[top--];
printf(“ the result is %f\n”, res);
}
c program to convert a prefix expression to its equivalent
postfix expression.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void push(char item[], int *top, char s[][20])
{ *top = *top + 1;
strcpy(s[*top], item);
}
char *pop(int *top, char s[][20])
{
return s[(*top)--];
}
void prefix_postfix(char prefix[], char postfix[])
{
char s[20][20]; //stack to hold the postfix expression
int top; // points to topmost item
char symbol; // Symbol scanned from prefix expression
char temp[2];// To convert symbol scanned into a string
char *op1;// Holds operand 1 obtained after popping
char *op2;// Holds operand 2 obtained after popping
int i; // Index to scan each symbol from prefix
top = -1; // Stack empty state
strrev(prefix);
for(i=0; i<strlen(prefix); i++)
{
symbol = prefix[i]; // Obtain the next symbol
temp[0] = symbol;
temp[1] = '\0';
switch(symbol)
{
case '+' :
case '-' :
case '*' :
case '/' :
case '^' :
op1 = pop(&top, s);
op2 = pop(&top, s);
int main()
{
char prefix[20], postfix[20];
printf("Enter the prefix expression \n");
scanf("%s", prefix);
prefix_postfix(prefix, postfix);
printf("The postfix expression is %s\n", postfix);
getch();
}
Ex; to check whether a give string is palindrome or not using
stack.
# include <stdio.h>
# include <string.h>
int is_palindrome( char str[])
{
int i, top = -1;
char s[30], stk_item;
/* push all the characters of the given string
for( i=0; i<strlen(str); i++ )
{
S[++top]= str[i];
}
/* check whether the string is palindrome or not.
for (i=0; i<strlen(str);i++)
{
Stk_item = s[top--];
if (str[i] != stk_item)
return 0;
}
return 1;
}
void main()
{
Char str[20];
printf(“enter string”);
Scanf(“%s”, str);
if (is_palindrome(str))
printf(“ the string is palindrome”);
else
printf(“ the string is not a palindrome”);
}
// c program to convert a postfix expression to its equivalent
infix expression.
#include <stdio.h>
#include<string.h>
/* include C functions implementing push and pop operations.
Void postfix_infix( char postfix[], char infix[])
{
char s[20][20] , symbol , temp[2] , op1 , op2 ;
int top , i ;
top = -1 ;
for ( i=0; i<strlen(postfix) ; i++ )
{
symbol = postfix[i];
temp[0] = symbol;
temp[1] = ‘\0’;
switch ( symbol )
{
case ‘+’ :
case ‘-’ :
case ‘*’ :
case ‘/’ :
case ‘^’ :
op2 = pop ( top , s );
op1 = pop ( top , s );