0% found this document useful (0 votes)
48 views

Unit 2 Stacks

Uploaded by

Lakpa Nuru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Unit 2 Stacks

Uploaded by

Lakpa Nuru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Course Structure and Contents:

Unit 1: Introduction to Data Structure [3 hours]

Data Types, Concept of data structure, Abstract Data Type, Implementation of Data Structure, Introduction to
algorithms, Basics of asymptotic notations.

Unit 2: The Stack [4 hours]

Definition, Stack as an ADT, Stack operations, Stack Application: Evaluation of infix, postfix, and prefix
expression, Conversion of infix to postfix/prefix expression.

Unit 3: Queue [3 hours]

Definition, Queue as an ADT, Primitive operations in Queue, Linear and Circular queue and their application,
Array Based queue implementation, Priority Queue.

1
Unit 4: Lists [9 hours]

Definition, Static and dynamic list structure, Array implementation of lists, Queues as list. Linked List and
linked list as an ADT, Types of Linked List: Singly Linked List, Circular Linked List, Doubly Linked Lists,
Basic operations in linked list: node insertion, deletion, insertion and deletion after and before nodes, Linked
stacks and queues using linked lists.

Unit 5: Recursion [3 hours]

Principle of Recursion, Comparison between recursion and iteration, Recursion example, Factorial, Fibonacci
sequence, GCD and Tower of Hanoi (TOH) Applications of Recursion.

Unit 6: Sorting [7 hours]

Introduction, Internal and External Sorting, Insertion Sort, Selection Sort, Bubble Sort, Merge Sort and Quick
Sort, Efficiency of Sorting algorithms.

Unit 7: Searching and Hashing [5 hours]

Introduction to Searching, Search algorithms: Sequential search, Binary search, Efficiency of different search
algorithms, Hashing: hash function, hash table, collision resolution techniques.

Unit 8: Trees [6 hours]

Concepts of tree, Basic operation in Binary tree,Tree height, level and depth, Tree search and
insertion/deletions, Binary tree traversals (pre-order, post-order and in-order), AVL balanced tree, Balancing
algorithm.

Unit 9: Graphs [8 hours]

Represention and applications, Graphs as an ADT, Graph types, Transitive closure, Warshall's algorithm,
Graph traversal, Minimum spanning tree: Kruskal's and Prims algorithms, Shortest-path algorithm Dijkstra's
Algorithm.

2
Laboratory Work:

1. Implementation of Stack
2. Implementation of Linear and Circular Queues
3. Implementation of list and link list: Singly and Doubly
4. Factorial, Fibonacci and TOH using Recursion
5. Implementation of different Sorting Algorithms
6. Implementation of Searching Algorithms
7. Implementation of Binary and AVL tree.
8. Implementation of Tree Traversals
9. Implementation of Graph and its Traversal.

Reference Books:

1. Y. Langsam, M.J. Augenstein and A. M. Tenenbaum, Data Structures using C and C++ 2 nd Edition.
2. G. W. Rowe, Introduction to Data Structure and Algorithms with C and C++.
3. Rajesh K. Shukla, Data Structures using C and C++.

3
Unit 2: The Stack [4 hours]
Definition, Stack as an ADT, Stack operations, Stack Application: Evaluation of infix, postfix, and prefix
expression, Conversion of infix to postfix/prefix expression.

Definition:

A stack is a linear data structure in which an element may be inserted or deleted only at one end called the top
of stack i.e. the elements are removed from stack in reverse order in which they are inserted into the stack. It
uses a variable called top which points the topmost element in the stack. Top is incremented while pushing
(inserting) an element into the stack and decremented while popping (removing) an element from the stack.
Real world scenarios of stack examples are as given;

Figure 1: Real World Stack Examples

A stack follows the principle of LIFO (Last In First Out). Majorly, there are two functions for "inserting" and
"deleting" elements are push and pop respectively. Figure below demonstrates how stack's push and pop are
performed;

Figure 2: Push and Pop operations of Stack.

4
Basic features of stack:

 Stack is an ordered list of similar data type.


 Stack is a LIFO (Last in First out) structure or we can say FILO (First in Last out).
 Stack has operations like push which inserts elements into stack and pop which deletes elements from
stack. Interesting fact is that, both push and pop are performed from one end called top of stack.
 Stack is said to be underflow if it does not have elements. (top of stack = -1)
 Stack is said to be overflow if it completely full. (top of stack = n-1)

Applications of Stack:

 To evaluate the postfix and prefix expressions.


 To keep the page-visited history in a web browser.
 To perform the undo sequence in a text editor (ctrl+z undo the recent edit).
 Used in recursion.
 To check the correctness of parentheses sequence.
 And many more.

Stack as an ADT

A stack is non-primitive data type and it contains elements of type T. It is a finite sequence of elements of T
type together with the operations as follows;

 CreateEmptyStack(S): create an empty stack S.


 Push(S, x): insert x into S at one end called its top.
 Top(S): it returns the index of top of the stack if stack is not empty.
 Pop(S): It removes the elements from Top.
 IsFull(S): Identify whether the stack S is full or not. It is a condition. Return true if full else false.
 IsEmpty(S): Condtion that checks whether the stack S is empty or not. If empty it return true else false.

POP and PUSH operation : POP and PUSH operation is done one by one. We cannot insert or delete elements
in bulk.

PUSH operation:

The push operation is used to insert the elements into the stack. There is a condition of "stack overflow", in
which the push operation cannot be performed. If stack is not overflow, then we can insert the elements one by
one by incrementing the value of Top by one until the condition "stack overflow" occurred. For stack
implementation array is used.

5
Algorithm for PUSH Operation:

Let Stack[maxsize] is an array to implement the stack. The variable top denotes the top of the stack. This
algorithm adds or inserts or push an item at the top of the stack.

1. Start Implementation of push algorithm in C-language


2. Check for stack overflow as
If top == maxsize-1 then void push(){
Print "Stack Overflow" int val;
if(top==maxsize){
exit the program
printf("Stack Overflow \n");
Else }
Increase top by 1 as, else{
Set, top=top+1 top=top+1;
3. Read elements to be inserted say x stack[top]=val;
4. Set, Stack[top]=x }
5. Stop }

POP operation:

Removal or deletion of element from the top of the stack is called pop operation. Unlike incrementing, the top is
decremented by 1 whenever an item is deleted from the stack. There is a condition called "Stack underflow or
empty" which is caused when there is no element in the stack. In that condition, pop operation cannot be
performed.

Algorithm for POP Operation:

The algorithm deletes the top elements of the stack and assigns it to a variable element.

1. Start
Implementation of pop algorithm in C-language
2. Check for the stack underflow as
If top<0 then
void pop(){
Print "Stack Underflow"
int item;
Exit the program
if(top<0){
Else
printf("The stack is underflow or empty");
Remove the top element
and set this element to the variable as }
Set, x = Stack[top] else{
Decrement the top by 1 as, item=stack[top];
Top=top-1 top=top-1;
3. Print 'x' is a deleted item from the stack printf("The popped item is = %d", item);
4. Stop }
}

6
PEEK or Display operation:

The display or peek operation involves returning the element which is present at the top of the stack without
deleting. Peek only displays the top elements without popping it.

Algorithm for PEEK Operation: Implementation of display algorithm in C-language


1. Start void display()
2. Check for the Stack Underflow as, {
If top<0 then
printf("The elements in the stack are:\n");
Print "Stack Underflow"
for (i = top; i >= 0; i--)
Else
{
Set, i=top
While i>=0 printf("%d\n", stack[i]);
Display stack[i] }
Decrement i by 1 as if (top == -1)
i=i-1 {
end while printf("Stack is underflow");
3. Stop }
}

Complete program that implements all the operations used in Stack implementation using array: [Menu
Driven Program]

#include <stdio.h>
void push();
void pop();
void display();

int stack[100], i, j, choice = 0, n, top = -1;

void main()
{
printf("Enter the number of elements in the stack:\n");
scanf("%d", &n);
printf("-----**Stack Operations using array**-----\n");
while (choice != 4)
{
printf("Choose \n1. Push \n2. Pop \n3. Peek \n4.Exit \n");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
7
break;
case 4:
printf("Exiting..");
break;
default:
printf("Invalid choice: \nEnter Valid Choice:");
}
}
}

void push()
{
int val;
if (top == n)
{
printf("Stack Overflow \n");
}
else
{
printf("Enter the value:\n");
scanf("%d", &val);
top = top + 1;
stack[top] = val;
}
}

void pop()
{
int item;
if (top < 0 || top == -1)
{
printf("The stack is underflow or empty");
}
else
{
item = stack[top];
top = top - 1;
printf("The popped item is = %d \n", item);
}
}

void display()
{
printf("The elements in the stack are:\n");
for (i = top; i >= 0; i--)
{
printf("%d\n", stack[i]);
}
if (top == -1)
{
8
printf("Stack is underflow");
}
}

Stack Application: Conversion and Evaluation of infix, postfix, and prefix expression.

There are a lot of computer applications of stack as described above but here we need to study about the
following applications:

 Conversion of infix expression to postfix expression


 Conversion of infix expression to prefix expression
 Conversion of postfix expression to infix expression
 Conversion of prefix expression to infix expression
 Evaluation of postfix expression
 Evaluation of infix expression
 Evaluation of prefix expression

Infix, Prefix and Postfix notation:

1. Infix Notation:
It is a simple mathematical notation of an expression where an operator is written in between the operands.
For example: a+b (a, b are operands and + is an operator).
2. Prefix Notation:
In this notation, an operator precedes the two operands. i.e. the operator is written before the operands. It is
also called polish notation. E.g. the equivalent prefix expression of a+b infix expression is +ab.
3. Postfix Notation:
Similarly, in postfix expression an operator is written after the two operands. So, the equivalent postfix
expression of a+b is ab+.
Note: Square brackets are used to indicate the portion of conversion in an expression.

Table 1: Conversion of an infix expression to Prefix and Postfix Expression.

Infix Expression Prefix Expression Postfix Expression


A+B*C+D A+[*BC]+D A+[BC*]+D
[+A*BC]+D [ABC*+]+D
++A*BCD [ABC*+D+
(A+B)*(C+D) [+AB]*[+CD] [AB+]*[CD+]
*+AB+CD AB+CD+*
A*B+C*D [*AB]+[*CD] [AB*]+[CD*]
+*AB*CD AB*CD*+

A+B+C+D [+AB]+C+D [AB+]+C+D


[++ABC]+D [AB+C+]+D
+++ABCD AB+C+D+

9
The above expressions are converted according to the PRECEDENCE RULE provided in the following Table.

Table 2: Precedence rule

Token Operator Precedence Associativity


[high to low]
(), [], -. Function call, array element, struct or union 17 Left-to-right
member
--,++ Increment, decrement 16 Left-to-right
!, ~, -+, &*, sizeof Logical not, one's complement, unary minus 15 Right-to-left
plus, address or indirection, size in bytes
(type) – (int) or (float),etc. Type cast 14 Left-to-right
*/% Multiplicative 13 Left-to-right
+- Binary add or subtract 12 Left-to-right
<< >> Shift 11 Left-to-right
>, >=, <, <= Relational 10 Left-to-right
!=, == Equality 9 Left-to-right
& Bitwise and 8 Left-to-right
^ Bitwise XOR 7 Left-to-right
| Bitwise OR 6 Left-to-right
&& Logical AND 5 Left-to-right
|| Logical OR 4 Left-to-right
?: Conditional , ternary 3 Right-to-left
=, +=, -=, *=, /=, %=, &=, Assignment 2 Right-to-left
^=
, Comma 1 Left-to-right

Associativity:

It describes the rule where operators with the same precedence appear in an expression. E.g. in an expression
A+B-C, both + and – have the same precedence, then which part of the expression is evaluated first is
determined by associativity. So the expression will be evaluated as (A+B)-C.

Exponentiation:

In case of exponentiation an expression has a right-to-left associativity. Let's understand through an example by
comparing it with binary addition or subtraction.

Binary add and subtract Exponentiation – ($ as exponential)


A+B-C A$B$C
(A+B)-C -> left to right A$(B$C) - right to left
e.g.
A=5
B=3
C=2

10
Precedence Rule for Exponentiation, Addition / Subtraction , and Multiplication/ Division is given in the
following table;

Operator Precedence Associativity


Exponentiation Highest Right Associative
Multiplication and Division Second Highest Left Associative
Addition and Subtraction Third Highest Left Associative

Let's illustrate some of the conversions of an expressions.

a. A+(B*C) – infix form


A+(BC*)
ABC*+ – postfix expression

b. (A+B)*((C-D)+E)/F – infix form


= (AB+)*((C-D)+E)/F
= (AB+)*((CD-)+E)/F
= (AB+)*(CD-E+)/F
= AB+CD-E+*/F – precedence rule for * and / is same so left to right associativity.
= AB+CD-E+*F/ – postfix expression

Stack Implementation:

I. Algorithm to convert infix to postfix notation.


1) Start
2) Scan the infix string from left to right
3) Initialize empty Stack
4) If the scanned character is an operand, add it to the postfix string.
5) If the scanned character is an operator and if the stack is empty, push the character to Stack.
6) If the scanned character is an operator and if the stack is not empty, compare the precedence of the
character with the element of the top of stack.
7) If top of stack symbol or element has highest precedence over the scanned character then pop the Stack
(top element) else push the scanned character to Stack.
8) Repeat 7 until the stack is not empty and top of stack as the highest precedence over the scanned
character.
9) Repeat step 4 and 8 till all the characters are scanned.
10) If the scanned character is opening bracket '(', no need to comparison just push it to stack. But if the
character is closing bracket ')' then pop out all the operators that are placed above the '(' opening bracket
in stack.
11) After all the characters are scanned, we have to add any character that the stack may have to the Postfix
string.
12) If the stack is not empty add top stack to postfix string and pop the stack.
13) Repeat step 12 as long as stack is not empty.
14) Stop

11
Tracing an Algorithm to convert infix to postfix notation:

Stack Input Output-Postfix Tracing steps


Notation
Empty A+(B*C-(D/E-F)*G)*H
Empty +(B*C-(D/E-F)*G)*H A Scanned character is an operand so added to postfix exp.
+ (B*C-(D/E-F)*G)*H A Character is operator so push to stack
+( B*C-(D/E-F)*G)*H A Parenthesis is an operator so pushed
+( *C-(D/E-F)*G)*H AB B is an operand so added to postfix exp. No need to compare
brackets to any other operators.
+(* C-(D/E-F)*G)*H AB Character * is an operator so pushed.
+(* -(D/E-F)*G)*H ABC Top stack(*) and scanned character (-) are compared
+(- (D/E-F)*G)*H ABC* Since * has high precedence so popped and – is pushed.
+(-( D/E-F)*G)*H ABC* Character ( is pushed
+(-( /E-F)*G)*H ABC*D Character D is an operand so added to postfix exp.
+(-(/ E-F)*G)*H ABC*D Character / pushed to stack
+(-(/ -F)*G)*H ABC*DE Character E is operand and added to postfix exp. And Top
stack(/) and scanned character (-) are compared
+(-(- F)*G)*H ABC*DE/ Since / has high precedence so popped and – is pushed.
+(-(- )*G)*H ABC*DE/F F is an operand so added to postfix exp.
+(- *G)*H ABC*DE/F- If Character is closing bracket ')' pop out the operators
between '(' and ')' from stack. Compare * and – precedence.
+(- * G)*H ABC*DE/F- Since – has low precedence than *, so * is pushed.
+(- * )*H ABC*DE/F-G G added to postfix exp.
+ *H ABC*DE/F-G*- All operators are popped out enclosed inside '(' and ')'.
+* H ABC*DE/F-G*- Since + has low precedence than *, so * is pushed.
+* End ABC*DE/F-G*-H H is added to postfix exp.
Empty End ABC*DE/F-G*-H*+ Stack is popped.

12
Another Way: Also, we can convert the provided infix expression to postfix expression using two different
stacks opstack and poststack.

Following is an algorithm that illustrates the conversion of infix to postfix using opstack(operator stack) and
poststack(output).

Algorithm to Convert infix to postfix notation using two separate stacks:

1. Start
2. Scan one character at a time of an infix expression from left to right.
3. Opstack=the empty stack
4. Repeat till there is data in infix expression
4.1 If scanned character is '(' then push it to opstack.
4.2 If scanned character is an operand then push it to poststack.
4.3 If scanned character is an operator then check
If(opstack!=-1)
While (precedence(opstack[tos]>=precedence(scanned character)) then
Pop and push it into poststack
Otherwise
Push scanned character into opstack
4.4 If scanned character is ')' then
Pop and push into poststack until '(' not found and ignore both symbols
5. Pop and push into poststack until opstack is not empty
6. Stop

Tracing of above algorithm with examples:

Example 1: ((A-(B+C))*D)$(E+F)

Scan character Poststack Opstack Steps and operations


( ---- ( 4.1
( ---- (( 4.1
A A (( 4.2
- A ((- 4.3
( A ((-( 4.1
B AB ((-( 4.2
+ AB ((-(+ 4.3
C ABC ((-(+ 4.2
) ABC+ ((- 4.4
) ABC+- ( 4.4
* ABC+- (* 4.3
D ABC+-D (* 4.2
) ABC+-D* -- 4.4
$ ABC+-D* $ 4.3
( ABC+-D* $( 4.1
E ABC+-D*E $( 4.2
+ ABC+-D*E $(+ 4.3
13
F ABC+-D*EF $(+ 4.2
) ABC+-D*EF+ $ 4.4
---- ABC+-D*EF+ --- 5

Example 2: (A+B*C$D)/((E+F-G)*H)$I/J

Scan Poststack Opstack Steps and operations


character
( ---- ( 4.1
A A ( 4.2
+ A (+ 4.3
B AB (+ 4.2
* AB (+* 4.3 prec(+)>prec(*) = false
C ABC (+* 4.2
$ ABC (+*$ 4.3 prec(*)>prec($) = false
D ABCD (+*$ 4.2
) ABCD$*+ ---- 4.4
/ ABCD$*+ / 4.3
( ABCD$*+ /( 4.1
( ABCD$*+ /(( 4.1
E ABCD$*+E /(( 4.2
+ ABCD$*+E /((+ 4.3
F ABCD$*+EF /((+ 4.2
- ABCD$*+EF+ /((- 4.3 prec(+)=prec(-) equal precedence, Associativity is Left-
right (+ is evaluated first because it is in left.) so + is popped.
G ABCD$*+EF+G /((- 4.2
) ABCD$*+EF+G- /( 4.4
* ABCD$*+EF+G- /(* 4.3
H ABCD$*+EF+G-H /(* 4.2
) ABCD$*+EF+G-H* / 4.4
$ ABCD$*+EF+G-H* /$ 4.3 prec(/)>prec($) = false
I ABCD$*+EF+G-H*I /$ 4.2
/ ABCD$*+EF+G-H*I$ // 4.3 prec($)>prec(/)=true, so $ is popped
prec(/)=prec(/) equal precedence, Associativity is Left-right
(left / is evaluated first because it is in left.)so / popped.
J ABCD$*+EF+G-H*I$J // 4.2
---- ABCD$*+EF+G-H*I$J/ / 5
---- ABCD$*+EF+G-H*I$J// ---- 5

Hence, the postfix expression of an infix expression ((A-(B+C))*D)$(E+F) is ABCD$*+EF+G-H*I$J//.

14
Implementation in C-programming to convert an expression from infix-postfix

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

int precedency(char);

void main(){
int i, otos = -1, ptos = -1, len, length;
char infix[100], poststack[100], opstack[100];
printf("Enter a valid infix expression: \n");
gets(infix);
length = strlen(infix);

for (i = 0; i <= length - 1; i++) {


if (infix[i] == '(') {
opstack[++otos] = infix[i]; // pre increment because otos=-1 opstack top of stack
}
else if (isalpha(infix[i])) { //for operand
poststack[++ptos] = infix[i]; // pre-increment because pstos=-1 poststack top of stack
}
else if (infix[i] == ')') {
while (opstack[otos] != '(') {
poststack[++ptos] = opstack[otos];
otos--;
}
otos--;
}
else { // for operators
if (precedency(opstack[otos]) >= precedency(infix[i])) {
poststack[++ptos] = opstack[otos--];
opstack[++otos] = infix[i];
}
else
opstack[++otos] = infix[i];
}
}

while (otos != -1) { // when there are no scanned characters in infix


poststack[++ptos] = opstack[otos];
otos--;
}

int poslen=strlen(poststack);
printf("The postfix Expression is:\n");
for (i = 0; i < poslen-1; i++) { // for displaying postfix expression
printf("%c", poststack[i]);

15
}
}
int precedency(char ch){
switch (ch) {
case '$':
return (4);
case '*':
case '/':
return (3);
case '+':
case '-':
return (2);
default:
return (1);
}
}
Output:
Enter a valid infix expression:
(A+B*C$D)/((E+F-G)*H)$/J
The postfix Expression is:
ABCD$*+EF+G-H*$J//

II. Converting an infix expression to prefix expression:


The precedence rule for converting an expression from infix to prefix is identical to that of infix to postfix. Only
changes from postfix conversion are that the operator is placed before the operands rather than after them. The
prefix of A+B-C is -+ABC.

Algorithm:
For this we have to use two stacks one as opstack and another as prestack and top of stack for both are
represented as otos and ptos respectively.
The opstack is used to store operators of given infix expression whereas prestack is used to store the converted
prefix expression.
1. Start
2. Scan one character at a time of an infix expression from right to left.
3. Opstack=the empty stack
4. Repeat till there is data in infix expression
4.1 If scanned character is ')' then push it to opstack.
4.2 If scanned character is an operand then push it to prestack.
4.3 If scanned character is an operator then check
If(opstack!=-1)
While (precedence(opstack[tos]>precedence(scanned character)) then
Pop and push it into prestack
Otherwise
Push scanned character into opstack

16
4.4 If scanned character is '(' then
Pop and push into prestack until ')' not found and ignore both symbols
5 Pop and push into prestack until opstack is not empty.
6 Pop and display prestack in reverse order which gives required prefix expression.
7 Stop.

Tracing
Example 1: (A+B*C$D)/((E+F-G)*H)$I/J
Scan prestack opstack Steps and operations
character
J J ------ 4.2
/ J / 4.3
I JI / 4.2
$ JI /$ 4.3 precedence(/)>precedence($) = false
) JI /$) 4.1
H JIH /$) 4.2
* JIH /$)* 4.3
) JIH /$)*) 4.1
G JIHG /$)*) 4.1
- JIHG /$)*)- 4.3
F JIHGF /$)*)- 4.2
+ JIHGF /$)*)-+ 4.3 precedence(-)>precedence(+) = false, both have equal.
E JIHGFE /$)*)-+ 4.2
( JIHGFE+- /$)* 4.4
( JIHGFE+-* /$ 4.4
/ JIHGFE+-*$ // 4.3 precedence($)>precedence(/) = true
) JIHGFE+-*$ //) 4.1
D JIHGFE+-*$D //) 4.2
$ JIHGFE+-*$D //)$ 4.3
C JIHGFE+-*$DC //)$ 4.2
* JIHGFE+-*$DC$ //)* 4.3 precedence($)>precedence(*) = true
B JIHGFE+-*$DC$B //)* 4.2
+ JIHGFE+-*$DC$B* //)+ 4.3 precedence(*)>precedence(+) = true
A JIHGFE+-*$DC$B*A //)+ 4.2
( JIHGFE+-*$DC$B*A+ // 4.4
---- JIHGFE+-*$DC$B*A+// ----- 5
----- //+A*B$CD$*-+EFGHIJ ----- 6

Example 2: ((A-(B+C))*D)$(E+F) – Class Task- Do by tracing an algorithm.

17
Implementation of Algorithm for converting infix to prefix expression in C-language.
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

int precedency(char);

void main()
{
int i, otos = -1, ptos = -1, length;
char infix[100], prestack[100], opstack[100];
printf("Enter a valid infix expression: \n");
gets(infix);
length = strlen(infix);

for (i = length - 1; i >=0; i--)


{
if (infix[i] == ')')
{
opstack[++otos] = infix[i]; // pre increment because otos=-1 opstack top of stack
}
else if (isalpha(infix[i]))//for operand
{
prestack[++ptos] = infix[i]; // pre-increment because pstos=-1 poststack top of stack
}
else if (infix[i] == '(')
{
while (opstack[otos] != ')')
{
prestack[++ptos] = opstack[otos];
otos--;
}
otos--;
}
else
{ // for operators
if (precedency(opstack[otos]) > precedency(infix[i]))
{
prestack[++ptos] = opstack[otos--];
opstack[++otos] = infix[i];
}
else
opstack[++otos] = infix[i];
}
}
while (otos != -1)
{ // when there are no scanned characters in infix
prestack[++ptos] = opstack[otos];
otos--;
18
}
int prelen=strlen(prestack);
printf("The prefix Expression is:\n");
for (i = prelen-1; i >=0; i--)
{ // for displaying postfix expression
printf("%c", prestack[i]);
}
}
int precedency(char ch)
{
switch (ch)
{
case '$':
return (4);
case '*':
case '/':
return (3);
case '+':
case '-':
return (2);
default:
return (1);
}
}

Output:
Enter a valid infix expression:
((A-(B+C))*D)$(E+F)
The prefix Expression is:
$*-A+BCD+EF

Enter a valid infix expression:


(A+B*C$D)/((E+F-G)*H)$I/J
The prefix Expression is:
//+A*B$CD$*-+EFGHIJ

III. Postfix to Infix Conversion:


There is an algorithm that is used to convert an expression from postfix to infix. The steps used are as follows;
1. Start
2. The postfix expression should be scanned from left to right.
3. If the symbol or character is an operand then it will be pushed into the stack.
4. If the symbol is an operator then
4.1 Pop the two operand op1 and op2 from the stack.
4.2 Put the operator between two recently popped operands and form a sub-expression or string like
(op1+op2) by wrapping it with parentheses.
4.3 Then push the string back to the stack.

19
5. After the completion of the iteration when the stack contains only one string then we can treat this string
or expression as an infix expression.
6. Display the result.
7. Stop.
Tracing of Algorithm:
Example 1: Convert the postfix expression AB+C*DE-FG+*- to infix algorithm.
Scanned Action Stack Explanation
Character
A Push A to stack A Step 3
B Push B to stack A,B Step 3
+ Pop B, Pop A , do (A+B) and push back to stack (A+B) Step 4
C Push C to stack (A+B),C Step 3
* Pop C and Pop (A+B) and do (A+B)*C and push back ((A+B)*C Step 4
to stack
D Push D to stack (A+B)*C,D Step 3
E Push E to stack (A+B)*C,D,E Step 3
- Pop E and Pop D and do (D-E) and push back to stack (A+B)*C,(D-E) Step 4
F Push F to stack (A+B)*C,(D-E),F Step 3
G Push G to stack (A+B)*C,(D-E),F,G Step 3
+ Pop G and Pop F and do (F+G) and push back (A+B)*C,(D-E),(F+G) Step 4
* Pop (F+G) and Pop (D-E) and do (F+G)*(D-E) and (A+B)*C, (D-E)*(F+G) Step 4
push back to stack
- Pop (F+G)*(D-E) and Pop (A+B)*C and do (A+B)*C- (A+B)*C- (D-E)*(F+G) Step 4
(F+G)*(D-E) and push back to stack

So the infix of AB+C*DE-FG+*- expression is (A+B)*C- (D-E)*(F+G) postfix expression.

Implementation of Postfix to infix conversion using C-language:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char stack[50];
int top = -1;

void push(char ch)


{
stack[++top] = ch;
}

char pop()
{
return stack[top--];
}

void convert(char exp[])


{
20
int l, i, j = 0;
char tmp[20];
strrev(exp);
l = strlen(exp);
printf("\nThe Infix Expression is : : ");

for (i = 0; i < l; i++)


{
if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/')
push(exp[i]);
else
{
tmp[j++] = exp[i];
tmp[j++] = pop();
}
}
strrev(tmp);
puts(tmp);
}

void main()
{
char exp[50];
printf("\nEnter the Postfix Expression : : ");
gets(exp);
convert(exp);
}

Output:

Enter the Postfix Expression : : ABC-+DE-FG-H+/*

The Infix Expression is : : A+B-C*D-E/F-G+H

Tracing the code for better understanding:

Array exp [] =

A B C - + D E - F G - H + \ *
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
index

Reverse Array exp [] =

* / + H - G F - E D + - C B A
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
index

21
Now the characters are scanned from reverse exp array as follows;

Scanned temp stack Actions


Character
* null * Operators are added to stack array
/ null *,/ Operators are added to stack array
+ null *, /, + Operators are added to stack array
H H, + *, / Operands are added to temp array and stack array is
popped at same time
- H, + *, /, - Operators are added to stack array
G H, +, G, - *, / Operands are added to temp array and stack array is
popped at same time
F H, +, G, -, F, / * Operands are added to temp array and stack array is
popped at same time
- H, +, G, -, F, / *, - Operators are added to stack array
E H, +, G, -, F, /, E, - * Operands are added to temp array and stack array is
popped at same time
D H, +, G, -, F, /, E, -, D, * null Operands are added to temp array and stack array is
popped at same time
+ H, +, G, -, F, /, E, -, D, * + Operators are added to stack array
- H, +, G, -, F, /, E, -, D, * +, - Operators are added to stack array
C H, +, G, -, F, /, E, -, D, *, C, - + Operands are added to temp array and stack array is
popped at same time
B H, +, G, -, F, /, E, -, D, *, C, -, B, + null Operands are added to temp array and stack array is
popped at same time
A H, +, G, -, F, /, E, -, D, *, C, -, B, +, A null Operands are added to temp array and stack array is
popped at same time

Here the reverse of tmp array = A+B-C*D-E/F-G+H, which is the infix expression as desired output.

IV. Prefix to Infix Conversion:


There is an algorithm that is used to convert an expression from postfix to infix. The steps used are as follows;
1. Start
2. The prefix expression should be scanned from right to left.
3. If the symbol or character is an operand then it will be pushed into the stack.
4. If the symbol is an operator then
4.1 Pop the two operand op1 and op2 from the stack.
4.2 Put the operator between two recently popped operands and form a sub-expression or string like
(op1+op2) by wrapping it with parentheses.
4.3 Then push the string back to the stack.
5. After the completion of the iteration when the stack contains only one string then we can treat this string
or expression as an infix expression.
6. Display the result.
7. Stop.

22
Tracing of Algorithm(Prefix to Infix):
Example 1: Convert the prefix expression //+A*B$CD$*-+EFGHIJ to infix algorithm. We need to scan from
right to left so lets reverse the expression as: JIHGFE+-*$DC$B*A+//
Scanned Action Stack Explanation
Character
J Push J to stack J Step 2
I Push I to stack J,I Step 2
H Push H to stack J,I,H Step 2
G Push G to stack J,I,H,G Step 2
F Push F to stack J,I,H,G,F Step 2
E Push E to stack J,I,H,G,F,E Step 2
+ Pop E, Pop F , do (E+F) and push back to stack J,I,H,G,(E+F) Step 4
- Pop (E+F), Pop G , do (E+F-G) and push back to J,I,H ,(E+F-G) Step 4
stack
* Pop (E+F-G), Pop H , do (E+F-G)*H and push J,I , (E+F-G)*H Step 4
back to stack
$ Pop (E+F-G)*H, Pop I , do (E+F-G)*H$I and J, (E+F-G)*H$I Step 4
push back to stack
D Push D to stack J, (E+F-G)*H$I, D Step 2
C Push C to stack J, (E+F-G)*H$I, D, C Step 2
$ Pop C, Pop D , do (C$D) and push back to stack J, (E+F-G)*H$I, (C$D) Step 4
B Push B to stack J, (E+F-G)*H$I, (C$D), B Step 2
* Pop B, Pop (C$D) , do (B*C$D) and push back J, (E+F-G)*H$I, (B*C$D) Step 4
to stack
A Push A to stack J, (E+F-G)*H$I, (B*C$D), A Step 2
+ Pop A, Pop (B*C$D), do A+(B*C$D) and push J, (E+F-G)*H$I, A+(B*C$D) Step 4
back to stack
/ Pop A+(B*C$D), Pop (E+F-G)*H$I, do J, A+(B*C$D)/ (E+F-G)*H$I Step 4
A+(B*C$D)/ (E+F-G)*H$I and push back to
stack
/ Pop A+(B*C$D)/ (E+F-G)*H$I, Pop J, do A+(B*C$D)/ (E+F-G)*H$I/J Step 4
A+(B*C$D)/ (E+F-G)*H$I/J and push back to
stack

Implementation of Prefix to infix conversion using C-language:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char stack[50];
int top = -1;

void push(char ch)


{
stack[++top] = ch;
}

23
char pop()
{
return stack[top--];
}

void convert(char exp[])


{
int l, i, j = 0;
char tmp[20];
l = strlen(exp);
printf("\nThe Infix Expression is : : ");
for (i = 0; i < l; i++)
{
if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/'||exp[i] == '$')
push(exp[i]);
else
{
tmp[j++] = exp[i];
tmp[j++] = pop();
}
}
puts(tmp);
}

void main()
{
char exp[50];
printf("\nEnter the Prefix Expression : : ");
gets(exp);
convert(exp);
}

Output:

Enter the Prefix Expression : : //+A*B$CD$*-+EFGHIJ

The Infix Expression is : : A+B*C$D/E+F-G*H$I/J

Tracing of Program above:

Tracing the code for better understanding:

Array exp [] =

/ / + A * B $ C D $ * - + E F G H I J
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
index

24
Now the characters are scanned from exp array as follows;

Scanned temp stack Actions


Character
/ Null / Operator is added to stack array
/ Null /, / Operator is added to stack array
+ Null /, /, + Operator is added to stack array
A A, + /, / Operand is added to temp array and stack
array is popped at same time
* A, + /, /, * Operator is added to stack array
B A, +, B, * /, / Operand is added to temp array and stack
array is popped at same time
$ A, +, B, * /, /, $ Operator is added to stack array
C A, +, B, *, C, $ /, / Operand is added to temp array and stack
array is popped at same time
D A, +, B, *, C, $, D, / / Operand is added to temp array and stack
array is popped at same time
$ A, +, B, *, C, $, D, / /, $ Operator is added to stack array
* A, +, B, *, C, $, D, / /, $, * Operator is added to stack array
- A, +, B, *, C, $, D, / /, $, *, - Operator is added to stack array
+ A, +, B, *, C, $, D, / /, $, *, -, + Operator is added to stack array
E A, +, B, *, C, $, D, /, E, + /, $, *, - Operand is added to temp array and stack
array is popped at same time
F A, +, B, *, C, $, D, /, E, +, F, - /, $, * Operand is added to temp array and stack
array is popped at same time
G A, +, B, *, C, $, D, /, E, +, F, -, G, * /, $ Operand is added to temp array and stack
array is popped at same time
H A, +, B, *, C, $, D, /, E, +, F, -, G, *, H, $ / Operand is added to temp array and stack
array is popped at same time
I A, +, B, *, C, $, D, /, E, +, F, -, G, *, H, $, I, / Null Operand is added to temp array and stack
array is popped at same time
J A, +, B, *, C, $, D, /, E, +, F, -, G, *, H, $, I, /, J Null Operand is added to temp array and stack
array is popped at same time

Here the tmp array = A+ B * C $ D / E + F - G * H $ I / J which is the infix expression as desired output.

V. Arithmetic Expression Evaluation:


The arithmetic expression can be evaluated using prefix and postfix expressions because infix notation is
ambiguous if parenthesis is not given. E.g. A+ (B*C) is evaluated and there are two results, one is 2+
(3*4) = 14 and (A+B)*C = (2+3)*4 = 20.
Note: Prefix notation is known as polish notation and postfix notation is known as reverse polish
notation.
Postfix and prefix expressions can be evaluated faster than an infix expression. This is because we don't
need to process any brackets or follow operator precedence rule.

25
 Evaluation of postfix expression
In postfix expressions we do not need any parenthesis, which ever operator comes after operands will be
evaluated first.
Manually evaluating postfix expression:
623+-382/+*2$3+
=65–382/+*2$3+
=1382/+*2$3+
=134+*2$3+
=17*2$3+
= 72$3+
= 49 3 +
= 52

Algorithm to evaluate the postfix expression:


Here, only one stack is used called vstack i.e. value stack.
1. Scan one character at a time from left to right of given postfix expression
1.1 If scanned character is operand then
- Read its corresponding value and push it into vstack
1.2 If scanned character is operator then
- Pop and assign into op2
- Pop and assign into op1
- Compute the result according to given operator and push result into vstack
2. Pop and display which is the required value of the given postfix expression.
3. Stop

Tracing the above algorithm of Evaluation of Postfix Expression.

Example: ABC+*CBA-+* = 123+*321-+*

Symbol Value Op2 Op1 Result vstack Steps


A 1 1 Step 1.1
B 2 1, 2 Step 1.1
C 3 1, 2, 3 Step 1.1
+ ……………. 3 2 5 1, 5 Op1+Op2, Step 1.2
* ……………. 5 1 5 5 Op1*Op2, Step 1.2
C 3 5, 3 Step 1.1
B 2 5, 3, 2 Step 1.1
A 1 5, 3, 2, 1 Step 1.1
- ……………. 1 2 1 5, 3, 1 Op1-Op2, Step 1.2
+ ……………. 1 3 4 5, 4 Op1+Op2, Step 1.2
* ……………. 4 5 20 20 Op1*Op2, Step 1.2, 2

So ABC+*CBA-+* = 123+*321-+* = 20 Answer.

26
Implementation of Evaluation of Postfix Expression:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>

int vstack[100];
int tos = -1;
void push(int val)
{
vstack[++tos] = val;
}
int pop()
{
return vstack[tos--];
}
void main()
{
int i, res, len, op1, op2, value[100];
char postfix[100], ch;
printf("Enter a proper postfix expression:: \t");
gets(postfix);
len = strlen(postfix);
for (i = 0; i < len; i++)
{
if (isalpha(postfix[i]))
{
printf("Enter the value of %c operand:\t", postfix[i]);
scanf("%d", &value[i]);
push(value[i]);
}
else
{
ch = postfix[i];
op2 = pop();
op1 = pop();
switch (ch)
{
case '+':
push(op1 + op2);
break;
case '-':
push(op1 - op2);
break;
case '*':
push(op1 * op2);
break;
case '/':
push(op1 / op2);
27
break;
case '%': // remainder
push(op1 % op2);
break;
case '$':
push(pow(op1, op2));
break;
}
}
}
printf("The result is: %d", pop());
}

Output:
Enter a proper postfix expression:: ab*c-d+
Enter the value of a operand: 1
Enter the value of b operand: 2
Enter the value of c operand: 3
Enter the value of d operand: 4
The result is: 3

 Evaluation of prefix expression


To evaluate the prefix expression is same as evaluating postfix expression only the difference is that here we
can scan one character from right to left instead of left to right and we set the first popped element in
operand 1 and second popped element in operand 2.

Algorithm to evaluate prefix algorithm:


Here, only one stack is used called vstack i.e. value stack.
1. Scan one character at a time from right to left of given prefix expression
1.1 If scanned character is operand then
- Read its corresponding value and push it into vstack
1.2 If scanned character is operator then
- Pop and assign into op1
- Pop and assign into op2
- Compute the result according to given operator and push result into vstack
2. Pop and display which is the required value of the given postfix expression.
3. Stop

Tracing the above algorithm of Evaluation of Prefix Expression.

Example: +A-/B$CD*E+F-/GHI where A=1, B=2, C=3, D=2, E=1, F=5, G=9, H=3, I=2

Symbol Value Op1 Op2 Result vstack Steps


I 2 ………… ………… ………… 2 Step 1.1
H 3 ………… ………… ………… 2, 3 Step 1.1
G 9 ………… ………… ………… 2, 3, 9 Step 1.1
28
/ ………… 9 3 3 2, 3 Op1/Op2, Step 1.2
- ………… 3 2 1 1 Op1-Op2, Step 1.2
F 5 ………… ………… ………… 1, 5 Step 1.1
+ ………… 5 1 6 6 Op1+ Op2, Step 1.2
E 1 ………… ………… ………… 6, 1 Step 1.1
* ………… 1 6 6 6 Op1*Op2, Step 1.2
D 2 ………… ………… ………… 6, 2 Step 1.1
C 3 ………… ………… ………… 6, 2, 3 Step 1.1
$ ………… 3 2 9 6, 9 Op1$Op2, Step 1.2
B 2 ………… ………… ………… 6, 9, 2 Step 1.1
/ ………… 2 9 0 6, 0 Op1/Op2, Step 1.2
- ………… 0 6 -6 -6 Op1-Op2, Step 1.2
A 1 ………… ………… ………… -6, 1 Step 1.1
+ ………… 1 -6 -5 -5 Op1+ Op2, Step 1.2, 2

So +A-/B$CD*E+F-/GHI = -5, where A=1, B=2, C=3, D=2, E=1, F=5, G=9, H=3, I=2.

Implementation of Evaluation of Prefix Expression in C-language:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>

int vstack[100];
int tos = -1;
void push(int val)
{
vstack[++tos] = val;
}
int pop()
{
return vstack[tos--];
}
void main()
{
int i, res, len, op1, op2, value[100];
char prefix[100], ch;
printf("Enter a proper prefix expression:: \t");
gets(prefix);

len = strlen(prefix);
for (i = len-1; i >= 0; i--)
{
if (isalpha(prefix[i]))//check for letters
{
printf("Enter the value of %c operand:\t", prefix[i]);
scanf("%d", &value[i]);
push(value[i]);//alphabet's value pushed into vstack stack
29
}
else
{
ch = prefix[i];//hold operators
op1 = pop();
op2 = pop();
switch (ch)
{
case '+':
push(op1 + op2);
break;
case '-':
push(op1 - op2);
break;
case '*':
push(op1 * op2);
break;
case '/':
push(op1 / op2);
break;
case '%': // remainder
push(op1 % op2);
break;
case '$':
push(pow(op1, op2));
break;
}
}
}
printf("The result is: %d", pop());
}

Output:
Enter a proper prefix expression :: +a-/b$cd*e+f-/ghi
Enter the value of i operand: 2
Enter the value of h operand: 3
Enter the value of g operand: 9
Enter the value of f operand: 5
Enter the value of e operand: 1
Enter the value of d operand: 2
Enter the value of c operand: 3
Enter the value of b operand: 2
Enter the value of a operand: 1
The result is: -5

30
 Evaluation of infix expression

An infix expression is evaluated using two stacks, one for operator and another for operands. An infix string or
expression is read in an array from which symbols/characters are fetched one by one and the following checks
are performed.

1. If the character is an operand, push it into operand stack.


2. If the character is an operator then do the following:
2.1 If the operator stack is empty then push it to the operator stack.
2.2 Else if the operators stack is not empty.
2.3 If the character's precedence is greater than or equal to the precedence of the stack top of the
operator stack, then push the character to the operator stack.
2.4 If the character's precedence is less than the precedence of the stack top of the operator then pop
two operands say op1 and op2 and perform operation specified by popped operation.
2.5 Push the operand in operand stack.
2.6 Repeat above steps until the symbol becomes less than the popped operator.
3. If the character is "(" then push it into the operator stack.
4. If the character is ")" then do process as explained above until the corresponding "(" is encountered in
operator stack. Now just pop out the "(".
5. Repeat the above steps until the operator stack is not empty.
6. Finally pop the value from the operand stack and return it.
7. Stop

Trace of algorithm:

Example 1: Evaluate the following infix algorithm.

A+B-C*(D+E-F/G), A=1, B=4, C=2, D=8, E=3, F=9, G=3.

Character Value Operator Stack Operand Stack Operand 2 Operand 1 Result Steps
A 1 1 1
+ + 1 2.1
B 4 1, 4 1
- +, - 1, 4 2.3
C 2 +, - 1, 4, 2 1
* +,-,* 1,4,2 2.3
( +,-,*, ( 1, 4, 2 3
D 8 +,-,*, ( 1, 4, 2, 8 1
+ +,-,*, (,+ 1, 4, 2, 8 2.3
E 3 +,-,*, (,+ 1, 4, 2, 8, 3 1
- +,-,*, (,+,- 1, 4, 2, 8, 3 2.3
F 9 +,-,*, (,+,- 1, 4, 2, 8, 3, 9 1
/ +,-,*, (,+,-,/ 1, 4, 2, 8, 3, 9 2.3
G 3 +,-,*, (,+,-,/ 1, 4, 2, 8, 3, 9, 3 1
) +,-,*, (,+ 1, 4, 2, 8, 3, 3 3 9 9/3=3 4
+,-,* 1, 4, 2, 8, 0 3 3 3-3=0 5
1, 4, 2, 8 0 8 8+0=8 5

31
+,- 1, 4, 16 8 2 2*8=16 5
+ 1,-12 16 4 4-16=- 5
12
null -11 -12 1 1-12=- 6
11

Let's check manually,

Solution:

A+B-C*(D+E-F/G)

= 1+4-2*(8+3-9/3)

= 1+4-2*(8+3-3)

= 1+4-2*(8+0)

= 1+4-2*8

= 1+4-16

= 1-12

= -11 Answer//

Example 2: Evaluate the following infix algorithm.

(A+B-C)*D+E-(F/G), A=1, B=4, C=2, D=8, E=3, F=9, G=3.

Character Value Operator Stack Operand Stack Operand 2 Operand 1 Result Steps
( ( null 3
A 1 ( 1 1
+ (, + 1 2.1
B 4 (, + 1, 4 1
- (, +, - 1, 4 2.3
C 2 (, +, - 1, 4, 2 1
) (, + 1, 2 2 4 4-2=2 4
….. (, + 1, 2 5
….. null 3 2 1 1+2=3 5
* * 3 2.1
D 8 * 3, 8 1
+ + 24 8 3 3*8=24 2.4
E 3 + 24, 3 1
- +, - 24, 3 2.3
( +, -, ( 24, 3 3
F 9 +, -, ( 24, 3, 9 1
/ +, -, (, / 24, 3, 9 2.3
32
G 3 +, -, (, / 24, 3, 9, 3 1
) +, - 24, 3, 3 3 9 9/3=3 4
…….. + 24, 0 3 3 3-3=0 5
……….. null 24 0 24 0+24=24 6

The popped value = 24.

Note: Implementation of infix expression can be done using two approaches:

1. Converting infix to postfix and evaluate using the Postfix Evaluation Algorithm.
2. Converting infix to prefix and evaluate using the Prefix Evaluation Algorithm.

33
Exercises:

1. What is stack? How it different from queue? Show that stack and queue are ADT.
2. How you can convert given infix expression into their equivalent postfix expression?
3. Explain what do you mean by LIFO and FIFO?
4. Evaluate the following postfix expressions using stack.
a. AB-CDEF/+G-*-H-
b. ABCD*-E/+F+GH/-
c. AB+C*DEFG*+/+H-
Where, A=4, B=8, C=2, D=5, E=6, F=9, G=1, H=3.
5. Convert the following infix expressions into prefix and postfix expressions.
a. A*(B+C)/
b. (A*(B+(C/D)))
6. Write a program to implement the operations of Stack.
7. Write down basic operations of stack and also describes push and pop functions of stack.
8. Trace the algorithm to convert given infix to postfix expressions:
a. (A+B)*C+D/(E+F*G)-H
b. A+((B-C*D)/E)+F-G/H
c. (A*B+C)/D-E/(F+G)
d. A-B-C*(D+E/F-G)-H
e. A*B/C+(D+E-(F*(G/H)))
f. ((H*((((A+((B+C)*D))*F)*G)*E))+J)
9. When stack is empty and is full? Describe the display algorithm in stack.
10. What are infix, prefix and postfix notations?
11. Explain the infix to postfix conversion expression with proper example.
12. Write a program to convert the infix expression to postfix expression.
13. Explain the infix to prefix conversion expression with proper example.
14. Write a program to convert the infix expression to prefix expression.
15. Explain the postfix evaluation algorithm with an implementation.
16. Explain the prefix evaluation algorithm with an implementation.
17. Which notation is best for computer applications, infix, and postfix or prefix notations? Why?

34

You might also like