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

Application of Stack

The document provides an introduction to data structures. It discusses that data structures organize data in a systematic way to allow for efficient use. Linear data structures like arrays, stacks, queues and linked lists organize elements sequentially, while nonlinear structures like trees and graphs allow for non-sequential relationships. Key concepts covered include primitive versus non-primitive data structures, the need for data structures to efficiently store and access large amounts of data, and classifications of common data structure types.

Uploaded by

Tony Stark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
216 views

Application of Stack

The document provides an introduction to data structures. It discusses that data structures organize data in a systematic way to allow for efficient use. Linear data structures like arrays, stacks, queues and linked lists organize elements sequentially, while nonlinear structures like trees and graphs allow for non-sequential relationships. Key concepts covered include primitive versus non-primitive data structures, the need for data structures to efficiently store and access large amounts of data, and classifications of common data structure types.

Uploaded by

Tony Stark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

INTRODUCTION

Data structure is a systematic way to organize data in order to use it efficiently.


Any data structure is designed to organize data to suit a specific purpose so that it
can be
accessed and worked within appropriate ways. In computer programming, a data
structure may be selected or designed to store for the purpose of working on it with
various algorithms.
A data structure is a specialized format for organizing and storing data. General
data structure types include the array, the file, the record, the table, the tree, and so
on. Any data structure is designed to organize data to suit a specific purpose so that
it can be accessed and worked with in appropriate ways. Data structure includes
both linear and nonlinear data structure. Linear data structure organizes their data
elements in a linear fashion, where data elements are attached one after the other.
Linear data structure includes arrays, stack, queue,linked list etc. In nonlinear data
structure, data elements are not organized in a sequential fashion. Here a data item
could be attached to several other data elements to reflect a special relationship
among them and all the data items cannot be traversed in a single run. Nonlinear
data structure includes trees and graphs.
Algorithms are generally created independent of underlying languages, i.e.
an algorithm can be implemented in more than one programming language. Search
– Algorithm to search an item in a data structure. Sort − Algorithm to sort items in
a certain order. Insert −Algorithm to insert item in a data structure. Algorithm is a
step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created
independent of underlying languages, i.e. an algorithm can be implemented in
more than one programming language.

INTRODUCTION TO DATA STRUCTURE


Data Structure is a systematic way to organize data in order to use it efficiently.
Any data structure is designed to organize data to suit a specific purpose so that it
can be accessed and worked with in appropriate ways. In computer programming,
a data structure may be selected or designed to store for the purpose of working on
it with various algorithms. Following terms are the foundation terms of a data
structure.
Interface - Each data structure has an interface. Interface represents the set of
operations that a data structure supports. An interface only provides the list of
supported
Operations , type of parameters they can accept and return types of these
operations.
Implementation-Implementation provides the internal representation of a data
structure. Implementation also provides the definition of the algorithms used in the
operations of the data structure.
CHARACTERISTICS OF A DATA STRUCTURE
Correctness-Data Structures implementation should implement its interface
correctly
Time Complexity- Running time or the execution time of operations of data
structure
must be small as possible.
Space Complexity-Memory usage of a data structure operation should be as
little as
possible.
NEED FOR DATA STRUCTURE
As applications are getting complex and data rich, there are three common
problems that applications face now a days.
Data Search-If the application is to search an item, it has to search an item in 1
million
(106) items every time slowing down the search. As data grows, search will
become
slower.
Processor Speed-Processor speed although being very high, falls limited if the
data grows to billion records.
Multiple Requests-As thousands of users can search data simultaneously on a
web server,even the fast server fails while searching the data. To solve the above
mentioned problems, structures come to rescue. Data can be organized in a data
structure in such a way that all items may not be required to be searched and the
required data can be searched almost instantly.
EXECUTION TIME CASES
There are three cases which are usually used to compare various data structure’s
execution time in a relative manner:
Worst Case-This is the scenario where a particular data structure operation takes
maximum time it can take. If an operation’s worst case time is f(n) then this
operation
will not take more than f(n) time, where f(n) represents function of n.
Average Case-This is the scenario depicting the average execution time of an
operation of a data structure .If an operation takes f (n) time in execution, then m
operation will take mf (n) time.
Best case-This is the scenario depicting the least possible execution time of an
operation of a data structure.If an operation takes f(n) time in execution, then the
actual operation may take time as the random number which would be maximum
as
f(n).
BASIC TERMINOLOGY
Data- Data are values or set of values.
Data Item-Data item refers to single unit of values.
Group Items-Data items that are divided into sub items are called as Group
Items.
Elementary items-Data items that cannot be divided are called as Elementary
Items.
Attribute and Entity-An entity is that which contains certain attributes or
properties
which may be assigned values.
Entity Set-An entity is that which contains certain attributes or properties which
may be
assigned values.
Entity Set-Entities of similar attributes form an entity set.
Field-Field is a single elementary unit of information representing an attribute of
an
entity.
Record-Record is a collection of field values of a given entity.
File- File is a collection of records of the entities in a given entity set.
CLASSIFICATION OF DATA STRUCTURE
Primitive data structure
The primitive data structures are known as basic data structures. These data
structures are
directly operated upon by the machine instructions. Normally, primitive data
structures have different representation on different computers.
Example of primitive data structure
Integer
Float
Character
Pointer
Non-Primitive data structure
The non-primitive data structures are highly developed complex data structures.
Basically, these
are developed from the primitive data structure. The non-primitive data structure is
responsible
for organizing the group of homogeneous and heterogeneous data elements.
Example of Non-primitive data structure:
Arrays
Lists
Files
Integer
The integers are signed or unsigned whole numbers with the specified range such
as 5, 39, -1917, 0 etc. They have no fractional parts. Integers can be positive or
negative but whether or not they can have negative values, it depends upon the
integer types.
Float
Float refers floating point or real number. It can hold a real number or a number
having
a fractional part like 3.112 or 588.001 etc. The decimal point signals that it is a
floating point number, not an integer. The number 15 is an integer but 15.0 is a
floating point number.
Character
It can store any member of the basic character set. If a character from this set is
stored in a character variable, its value is equivalent to the integer code of that
character basically known as ASCII code. It can hold one letter/symbol like a, b ,c
,d etc. Characters can also be of different types.
Pointer
A pointer is but a variable-like name points or represents a storage location in
memory (RAM).RAM contains many cells to store values. Each cell in memory is
1 byte and has a unique address to identify it. The memory address is always an
unsigned integer.
Linear Data Structure
Linear data structures organize their data elements in a linear fashion, where data
elements are attached one after the other. Data elements in a linear data structure
are traversed one after the other and only one element can be directly reached
while traversing.
Arrays- An array is a collection of data elements where each element could be
identified
using an index
Linked List- A linked list is a sequence of nodes, where each node made up of a
data
element and a reference to the next node in a sequence.
Stack- Stack is actually a list where data elements can only be added or removed
from
top of the list.
Queue- A queue is also a list, where data elements can be added from one end of
the list
and removed from the other end of the list.
Non Linear Data Structure
In nonlinear data structures, data elements are not organized in a sequential
fashion. A data item in a nonlinear data structure could be attached to several other
data
elements to reflect a special relationship among them and all the data items cannot
be traversed in a single run. Data structures like trees and graphs are some
examples of widely used nonlinear data structure.
Trees- A tree is a data structure that is made up of a set of linked nodes which
can be
used to represent a hierarchical relationship among data elements.
Graph- A graph is a data structure that is made up of a finite set of edges and
vertices.
Edges represent connections or relationships among vertices that stores data
elements.

Classification
LINEAR DATA STRUCTURE
Arrays
Arrays are the set of homogeneous data elements stored in RAM. So, they can hold
only one type of data. The data may be all integers, all floating numbers or all
characters. Values in an array are identified using array name with subscripts.
Single sub-scripted variables are known as
a one-dimensional array or linear array; two sub-scripted variables are referred as a
two dimensional array.
 One Dimensional Array
 Two Dimensional Array

List
A list is a collection of a variable number of data items. Lists fall in the non-
primitive type of data structure in the classification of data structure. Every
element on a list contains at least two fields, one is used to store data and the other
one is used for storing the address of next element.

Files
Files contain data or information, stored permanently in the secondary storage
device such as Hard Disk and Floppy Disk. It is useful when we have to store and
process a large amount of data. A file stored in a storage device is always
identified using a file name like HELLO.DAT or TEXTNAME.TXT and so on.
A file name normally contains a primary and a secondary name which is separated
by a dot (.).
Stack
Like arrays, a stack is also defined as an ordered collection of elements. A stack is
a nonprimitive linear data structure having a special feature that we can delete and
insert elements from only one end, referred as TOP of the stack. The stack is also
known as Last In First Out (LIFO) type of data structure for this behavior.
When we perform insertion or deletion operation on a stack, its base remains
unchanged but the top of the stack changes. Insertion in a stack is called Push and
deletion of elements from the stack is known as Pop.
We can implement a stack using 2 ways
Static implementation (using arrays)
Dynamic implementation (using pointers)

Queues
Queues are also non-primitive linear data structure. But unlike stacks, queues are
the
First In First Out (FIFO) type of data structures. We can insert an element in a
queue from the REAR end but we have to remove an element from the only
FRONT end.
We can also implement queues using 2 ways
Using arrays
Using pointers
NON LINEAR DATA STRUCTURE
Trees
Trees fall into the category of non-primitive non-linear data structures in the
classification of data structure. They contain a finite set of data items referred as
nodes. We can represent a hierarchical relationship between the data elements
using trees.
A Tree has the following characteristics
The top item in a hierarchy of a tree is referred as the root of the tree.
The remaining data elements are partitioned into a number of mutually exclusive
subsets and they itself a tree and are known as the sub tree.
Unlike natural trees, trees in the data structure always grow in length towards
the bottom.

Graph
Graph falls in the non-primitive non-linear type of data structure in the
classification of data structure. Graphs are capable of representing different types
of physical structures. Apart from computer science, they are used broadly in the
fields of Geography, Chemistry & Engineering Sciences. A graph normally a
combination of the set of vertices V and set of edges E.
STACK DATA STRUCTURE INTRODUCTION
Stack is a linear data structure which follows a particular order in which the
operations are performed. The order may be LIFO(Last In First Out) or FILO(First
In Last Out).
Mainly the following three basic operations are performed in the stack:
 Push: Adds an item in the stack. If the stack is full, then it is said to be an
Overflow condition.
 Pop: Removes an item from the stack. The items are popped in the reversed
order in which they are pushed. If the stack is empty, then it is said to be an
Underflow condition.
 Peek or Top: Returns top element of stack.
 Is Empty: Returns true if stack is empty, else false.

HOW TO IMPLEMENT STACK PRACTICALLY?


There are many real-life examples of a stack. Consider the simple example of
plates stacked over one another in a canteen. The plate which is at the top is the
first one to be removed, i.e. the plate which has been placed at the bottommost
position remains in the stack for the longest period of time. So, it can be simply
seen to follow LIFO/FILO order.
Time Complexities of operations on stack:
push(), pop(), is Empty() and peek() all take O(1) time. We do not run any loop in
any of these operations.
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.
 Other applications can be Backtracking, Knight tour problem, rat in a maze, N
queen problem and sudoku solver
 In Graph Algorithms like Topological Sorting and Strongly Connected
Components

In a stack, only limited operations are performed because it is restricted data


structure. The elements are deleted from the stack in the reverse order.
Following are the applications of stack:

1. Expression Evaluation
2. Expression Conversion
i. Infix to Postfix
ii. Infix to Prefix
iii. Postfix to Infix
iv. Prefix to Infix
3. Backtracking
4. Memory Management

Expression Representation

There are three popular methods used for representation of an expression:

Infix A+B Operator between operands.


Prefix +AB Operator before operands.
Postfix AB + Operator after operands.

1. Conversion of Infix to Postfix


Algorithm for Infix to Postfix

Step 1: Consider the next element in the input.

Step 2: If it is operand, display it.

Step 3: If it is opening parenthesis, insert it on stack.

Step 4: If it is an operator, then


 If stack is empty, insert operator on stack.
 If the top of stack is opening parenthesis, insert the operator on stack
 If it has higher priority than the top of stack, insert the operator on stack.
 Else, delete the operator from the stack and display it, repeat Step 4.
Step 5: If it is a closing parenthesis, delete the operator from stack and display
them until an opening parenthesis is encountered. Delete and discard the opening
parenthesis.

Step 6: If there is more input, go to Step 1.

Step 7: If there is no more input, delete the remaining operators to output.

Example: Suppose we are converting 3*3/(4-1)+6*2 expression into postfix form.

Following table shows the evaluation of Infix to Postfix:

Expression Stack Output


3 Empty 3
* * 3
3 * 33
/ / 33*
( /( 33*
4 /( 33*4
- /(- 33*4
1 /(- 33*41
) - 33*41-
+ + 33*41-/
6 + 33*41-/6
* +* 33*41-/62
2 +* 33*41-/62
Empty 33*41-/62*+

So, the Postfix Expression is 33*41-/62*+

Example: Program for Infix to Postfix Conversion

#include <stdio.h>
#include <ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
push(char elem)
{
s[++top]=elem;
return 0;
}
char pop()
{
return(s[top--]);
}
int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
return 0;
}
void main()
{
char infx[50], pofx[50], ch, elem;
int i=0, k=0;
printf("\n\nEnter Infix Expression: ");
scanf("%s",infx);
push('#');
while( (ch=infx[i++]) != '\0')
{
if( ch == '(') push(ch);
else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
pofx[k++]=pop();
elem=pop();
}
else
{
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#')
pofx[k++]=pop();
pofx[k]='\0';
printf("\n\n Given Infix Expression: %s \n Postfix Expresssion:
%s\n",infx,pofx);
}

Output:

2. Infix to Prefix
Algorithm for Infix to Prefix Conversion:

Step 1: Insert “)” onto stack, and add “(” to end of the A .

Step 2: Scan A from right to left and repeat Step 3 to 6 for each element of A until
the stack is empty .

Step 3: If an operand is encountered, add it to B .

Step 4: If a right parenthesis is encountered, insert it onto stack .

Step 5: If an operator is encountered then,


a. Delete from stack and add to B (each operator on the top of stack) which
has same or higher precedence than the operator.
b. Add operator to stack.

Step 6: If left parenthesis is encountered then ,


a. Delete from the stack and add to B (each operator on top of stack until a
left parenthesis is encountered).
b. Remove the left parenthesis.

Step 7: Exit

Example: Program for Infix to Prefix Conversion

#include<stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#define MAX 50
struct infix
{
char target[MAX] ;
char stack[MAX] ;
char *s, *t ;
int top, l ;
};
void initinfix ( struct infix * ) ;
void setexpr ( struct infix *, char * ) ;
void push ( struct infix *, char ) ;
char pop ( struct infix * ) ;
void convert ( struct infix * ) ;
int priority ( char c ) ;
void show ( struct infix ) ;
void main( )
{
struct infix q ;
char expr[MAX] ;
clrscr( ) ;
initinfix ( &q ) ;
printf ( "\nEnter an expression in infix form: " ) ;
gets ( expr ) ;
setexpr ( &q, expr ) ;
convert ( &q ) ;
printf ( "The Prefix expression is: " ) ;
show ( q ) ;
getch( ) ;
}
/* initializes elements of structure variable */
void initinfix ( struct infix *pq )
{
pq -> top = -1 ;
strcpy ( pq -> target, "" ) ;
strcpy ( pq -> stack, "" ) ;
pq -> l = 0 ;
}
/* reverses the given expression */
void setexpr ( struct infix *pq, char *str )
{
pq -> s = str ;
strrev ( pq -> s ) ;
pq -> l = strlen ( pq -> s ) ;
*( pq -> target + pq -> l ) = '\0' ;
pq -> t = pq -> target + ( pq -> l - 1 ) ;
}
/* adds operator to the stack */
void push ( struct infix *pq, char c )
{
if ( pq -> top == MAX - 1 )
printf ( "\nStack is full.\n" ) ;
else
{
pq -> top++ ;
pq -> stack[pq -> top] = c ;
}
}
/* pops an operator from the stack */
char pop ( struct infix *pq )
{
if ( pq -> top == -1 )
{
printf ( "Stack is empty\n" ) ;
return -1 ;
}
else
{
char item = pq -> stack[pq -> top] ;
pq -> top-- ;
return item ;
}
}
/* converts the infix expr. to prefix form */
void convert ( struct infix *pq )
{
char opr ;
while ( *( pq -> s ) )
{
if ( *( pq -> s ) == ' ' || *( pq -> s ) == '\t' )
{
pq -> s++ ;
continue ;
}
if ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s ) ) )
{
while ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s ) ) )
{
*( pq -> t ) = *( pq -> s ) ;
pq -> s++ ;
pq -> t-- ;
}
}
if ( *( pq -> s ) == ')' )
{
push ( pq, *( pq -> s ) ) ;
pq -> s++ ;
}
if ( *( pq -> s ) == '*' || *( pq -> s ) == '+' || *( pq -> s ) == '/' ||*( pq -> s ) ==
'%' || *( pq -> s ) == '-' || *( pq -> s ) == '$' )
{
if ( pq -> top != -1 )
{
opr = pop ( pq ) ;
while ( priority ( opr ) > priority ( *( pq -> s ) ) )
{
*( pq -> t ) = opr ;
pq -> t-- ;
opr = pop ( pq ) ;
}
push ( pq, opr ) ;
push ( pq, *( pq -> s ) ) ;
}
else
push ( pq, *( pq -> s ) ) ;
pq -> s++ ;
}
if ( *( pq -> s ) == '(' )
{
opr = pop ( pq ) ;
while ( opr != ')' )
{
*( pq -> t ) = opr ;
pq -> t-- ;
opr = pop ( pq ) ;
}
pq -> s++ ;
}
}
while ( pq -> top != -1 )
{
opr = pop ( pq ) ;
*( pq -> t ) = opr ;
pq -> t-- ;
}
pq -> t++ ;
}
/* returns the priotity of the operator */
int priority ( char c )
{
if ( c == '$' )
return 3 ;
if ( c == '*' || c == '/' || c == '%' )
return 2 ;
else
{
if ( c == '+' || c == '-' )
return 1 ;
else
return 0 ;
}
}
/* displays the prefix form of given expr. */
void show ( struct infix pq )
{
while ( *( pq.t ) )
{
printf ( " %c", *( pq.t ) ) ;
pq.t++ ;
}
}
Output:

Postfix to Infix
Following is an algorithm for Postfix to Infix conversion:

Step 1: While there are input symbol left.

Step 2: Read the next symbol from input.

Step 3: If the symbol is an operand, insert it onto the stack.

Step 4: Otherwise, the symbol is an operator.


Step 5: If there are fewer than 2 values on the stack, show error /* input not
sufficient values in the expression */

Step 6: Else,
a. Delete the top 2 values from the stack.
b. Put the operator, with the values as arguments and form a string.
c. Encapsulate the resulted string with parenthesis.
d. Insert the resulted string back to stack.

Step 7: If there is only one value in the stack, that value in the stack is the desired
infix string.

Step 8: If there are more values in the stack, show error /* The user input has too
many values */

Example: Suppose we are converting efg-+he-sh-o+/* expression into Infix.

Following table shows the evaluation of Postfix to Infix:

efg-+he-sh-o+/* NULL
fg-+he-sh-o+/* “e”
g-+he-sh-o+/* “f”
“e”
-+he-sh-o+/* “g”
“f”
“e”
+he-sh-o+/* “f”-“g”
“e”
he-sh-o+/* “e+f-g”
e-sh-o+/* “h”
“e+f-g”
-sh-o+/* “e”
“h”
“e+f-g”
sh-o+/* “h-e”
“e+f-g”
h-o+/* “s”
“h-e”
“e+f-g”
-o+/* “h”
“s”
“h-e”
“e+f-g”
o+/* “h-s”
“h-e”
“e+f-g”
+/* “o”
“s-h”
“h-e”
“e+f-g”
/* “s-h+o”
“h-e”
“e+f-g”
* “(h-e)/( s-h+o)”
“e+f-g”
NULL “(e+f-g)* (h-e)/( s-h+o)”

So, the Infix Expression is (e+f-g)* (h-e)/(s-h+o)


Example: Program for Postfix to Infix conversion

#include <stdio.h>
#include <stdlib.h>
int top = 10;
struct node
{
char ch;
struct node *next;
struct node *prev;
} *stack[11];
typedef struct node node;
void push(node *str)
{
if (top <= 0)
printf("Stack is Full ");
else
{
stack[top] = str;
top--;
}
}
node *pop()
{
node *exp;
if (top >= 10)
printf("Stack is Empty ");
else
exp = stack[++top];
return exp;
}
void convert(char exp[])
{
node *op1, *op2;
node *temp;
int i;
for (i=0;exp[i]!='\0';i++)
if (exp[i] >= 'a'&& exp[i] <= 'z'|| exp[i] >= 'A' && exp[i] <= 'Z')
{
temp = (node*)malloc(sizeof(node));
temp->ch = exp[i];
temp->next = NULL;
temp->prev = NULL;
push(temp);
}
else if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/' || exp[i] == '^')
{
op1 = pop();
op2 = pop();
temp = (node*)malloc(sizeof(node));
temp->ch = exp[i];
temp->next = op1;
temp->prev = op2;
push(temp);
}
}
void display(node *temp)
{
if (temp != NULL)
{
display(temp->prev);
printf("%c", temp->ch);
display(temp->next);
}
}
void main()
{
char exp[50];
clrscr();
printf("Enter the postfix expression :");
scanf("%s", exp);
convert(exp);
printf("\nThe Equivalant Infix expression is:");
display(pop());
printf("\n\n");
getch();
}

Output:

4. Prefix to Infix

Expression Stack
-bc+-pqr Empty
/-bc+-pq “q”
“r”
/-bc+- “p”
“q”
“r”
/-bc+ “p-q”
“r”
/-bc “p-q+r”
/-b “c”
“p-q+r”
/- “b”
“c”
“p-q+r”
/ “b-c”
“p-q+r”
NULL “((b-c)/((p-q)+r))”
Algorithm for Prefix to Infix Conversion

Step 1: The reversed input string is inserted into a stack -> prefixToInfix(stack)

Step 2: If stack is not empty,


a. Temp -> pop the stack
b. If temp is an operator,
Write a opening parenthesis “(“ to show -> prefixToInfix(stack)
Write temp to show -> prefixToInfix(stack)
Write a closing parenthesis “)” to show
c. Else If temp is a space ->prefixToInfix(stack)
d. Else, write temp to show if stack.top != space ->prefixToInfix(stack)

Example: Suppose we are converting /-bc+-pqr expression from Prefix to Infix.

Following table shows the evaluation of Prefix to Infix Conversion:

So, the Infix Expression is ((b-c)/((p-q)+r))

Example: Program for Prefix to Infix Conversion

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

char opnds[50][80], oprs[50];


int topr=-1, topd=-1;
pushd(char *opnd)
{
strcpy(opnds[++topd],opnd);
}
char *popd()
{
return(opnds[topd--]);
}
pushr(char opr)
{
oprs[++topr]=opr;
}
char popr()
{
return(oprs[topr--]);
}
int empty(int t)
{
if( t == 0) return(1);
return(0);
}
void main()
{
char prfx[50],ch,str[50],opnd1[50],opnd2[50],opr[2];
int i=0,k=0,opndcnt=0;
clrscr();
printf("Enter Prefix Expression = ");
gets(prfx);
printf(" Given Prefix Expression is : %s\n",prfx);
while( (ch=prfx[i++]) != '\0')
{
if(isalnum(ch))
{
str[0]=ch; str[1]='\0';
pushd(str); opndcnt++;
if(opndcnt >= 2)
{
strcpy(opnd2,popd());
strcpy(opnd1,popd());
strcpy(str,"(");
strcat(str,opnd1);
ch=popr();
opr[0]=ch;opr[1]='\0';
strcat(str,opr);
strcat(str,opnd2);
strcat(str,")");
pushd(str);
opndcnt-=1;
}
}
else
{
pushr(ch);
if(opndcnt==1)opndcnt=0; /* operator followed by single operand*/
}
}
if(!empty(topd))
{
strcpy(opnd2,popd());
strcpy(opnd1,popd());
strcpy(str,"(");
strcat(str,opnd1);
ch=popr();
opr[0]=ch;opr[1]='\0';
strcat(str,opr);
strcat(str,opnd2);
strcat(str,")");
pushd(str);
}
printf(" Infix Expression: ");
puts(opnds[topd]);
getch();
}

Output:

You might also like