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

DSU Unit 3 Stack

A stack is a linear data structure that follows the LIFO (last-in, first-out) principle. Elements can only be inserted and removed from one end, called the top. Common stack operations include push to add an element and pop to remove an element. Stacks have many applications, such as reversing a string by pushing characters onto a stack and then popping them off in reverse order. Stacks can be implemented using arrays, where a top pointer tracks the current top element and operations ensure the stack doesn't overflow or underflow.

Uploaded by

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

DSU Unit 3 Stack

A stack is a linear data structure that follows the LIFO (last-in, first-out) principle. Elements can only be inserted and removed from one end, called the top. Common stack operations include push to add an element and pop to remove an element. Stacks have many applications, such as reversing a string by pushing characters onto a stack and then popping them off in reverse order. Stacks can be implemented using arrays, where a top pointer tracks the current top element and operations ensure the stack doesn't overflow or underflow.

Uploaded by

Mayur Narsale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Course : Data Structures Using ‘C’ 3.

Stack Course Code:22317

3. STACK
An array is a random access data structure, where each element can be accessed
directly and in constant time. A typical illustration of random access is a book - each page of
the book can be open independently of others. Random access is critical to many algorithms,
for example binary search.

A linked list is a sequential access data structure, where each element can be accessed
only in particular order.

A stack is a basic data structure that can be logically thought as linear structure
represented by a real physical stack or pile, a structure where insertion and deletion of items
takes place at one end called top of the stack. The basic concept can be illustrated by thinking
of your data set as a stack of plates or books where you can only take the top item off the
stack in order to remove things from it.

Definition :- Stack is an ordered collection of elements where the addition and deletion of
existing element is always takes place at the same end called as top of the stack.

The basic implementation of a stack is also called a LIFO (Last In First Out) to
demonstrate the way it accesses data. There are basically three operations that can be
performed on stacks .They are

1) inserting an item into a stack (push).


2) deleting an item from the stack (pop).
3) displaying the contents of the stack.

Basic terminologies related to stack :-


1) Maxsize :- The term is refer to the maximum size of stack.
2) Stack empty or underflow :- If the stack has no element & pop operation is called then
the condition is called as stack underflow.
3) Stackfull or overflow :- If the stack is full and push operation is called then the
condition is called as stack overflow.

Stack as abstract data type :- stack can be defined as abstract data type. Stack of an element
of any particular type is finite sequence of that type together with following operations
1) Initialize stack

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 1


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

2) Determine whether stack is empty or not


3) Determine whether stack is full or not
4) If stack is not full then insert the element using push operation from the top of the
stack
5) If stack is not empty then delete the element using pop operation from the top of the
stack

Primitive operations on stack :-


1) Createstack() :- To initialize the stack is an empty stack by initializing top = -1.
2) Deletion (pop) :- The process of deleting an element from the stack is called as
POP operation .After every pop operation top is decremented by 1.
3) Top :- Top is a pointer , which keeps track of top element in the stack. If array of
N elements is declared , then top will be -1 when it is empty and N when it is full.
4) Isempty() :- This function is used to check whether it is empty or not. This
function returns boolean value true if stack is empty else returns false.
5) Isfull() :- This function is used to check whether it is full or not. This function
returns boolean value true if stack is full else returns false.

Representation of stack using array :-


 Implementation of stack can be done in many ways. One of the simplest way is using
arrays. Array is initialized with maximum value first.

 Function to insert an element into the stack :-


Before inserting any element into the stack we must check whether the stack is full. In
such case we cannot enter element into the stack. If the stack is not full then we must
increase position of top by 1 and then insert the element.

int stack_full(int top)


{
if(top==MAX-1)
{
printf("\n Stack is full");
exit(0);
}
else
return (1);
}

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 2


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

The function returns 1 if stack is not full. The top


varies from 0 to MAX-1. Hence top at MAX-1 denotes that
stack is full.

void push()
{
if(top==MAX-1)
printf("\n Stack is full");
else
{
printf("\n Enter the number:-:");
scanf("%d",&no);
top++;
stack[top]=no;
}
}

 Function to delete an element into the stack :-


Before deleting element from the stack we must check whether the stack is empty or
not. If stack is empty then we can not delete element from the stack. If stack is not
empty , we can delete element by decrementing position of top.

int stack_empty(int top)


{
if(top==-1)
{
printf("\n Stack is empty");
exit(0);
}
else
return (1);
}
This function nreturns 1 if the stack is not empty. The
top varies from 0 to MAX-1. Hence top at -1 denotes that
stack is empty.

void pop()
{
if(top==-1)
printf("\n Stack is empty");
else
{
no=stack[top];
top--;

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 3


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

}
}

 Function to display elements of the stack :-

void display()
{
if(top==-1)
printf("\n Stack is empty");
else
{
for(i=top;i>=0;i--)
printf("\n %d",stack[i]);
}
}

 Program for stack implementation :-

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
int stack[MAX],top=-1,i=0,choice,no;
char ans;
void push();
void pop();
void display();
void push()
{
if(top==MAX-1)
printf("\n Stack is full");
else
{
printf("\n Enter the number:-:");
scanf("%d",&no);
top++;
stack[top]=no;
}
}
void pop()
{
if(top==-1)
printf("\n Stack is empty");
else
{
no=stack[top];
top--;

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 4


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

}
}
void display()
{
if(top==-1)
printf("\n Stack is empty");
else
{
for(i=top;i>=0;i--)
printf("\n %d",stack[i]);
}
}
void main()
{
clrscr();
do
{
printf("\n 1.PUSH");
printf("\n 2.POP");
printf("\n 3.DISPLAY");
printf("\n 4.EXIT");
printf("\n ENTER YOUR CHOICE");
scanf("%d", &choice);
switch(choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\n Invalid choice");
break;
}
printf("\n do you want to continue [y/n]");
ans=getche();
}
while(ans=='Y'||ans=='y');
getch();
}

Applications of stack :-

1) Reverse of a string :-
One of the simple application of the stack is reverse of a string. It can simply be done
by pushing the individual characters of the string one by one on to the stack, till end
of string is reached and the elements of the stack are popped off.
For e.g. “REAL “

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 5


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Here first perform the push operation.

Input string Character being read Stack


REAL R

(Push R)
R
REAL E

(Push E) E
R
REAL A
↑ A
(Push A) E
R
REAL L L
↑ A
(Push L) E
R
Now perform the pop operation .

Stack Popped character Reversed string


L
A L L
E ↑
R
(POP L)

A
E A LA
R ↑
(POP A)

E E LAE
R ↑
(POP E)

R LAER
R ↑
(POP R)

Therefore the resulting reversed string is “LAER”.

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 6


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Program for reverse of string :-

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10
char stack[MAX],str[10];
int top=-1,i=0,l=0;
void push(char);
char pop();
void push (char t1)
{
if(top==MAX-1)
{
printf("\n Stack is full");
}
else
{
top++;
stack[top]=t1;
}
}
char pop()
{
char t2;
if(top==-1)
{
printf("\n Stack is empty");
}
else
{
t2=stack[top];
top--;
}
return (t2);
}
void main()
{
clrscr();
printf("\n Enter String :-");
gets(str);
l=strlen(str);
printf("\n Length of string is %d:- ",l);
for(i=0;i<l;i++)
{
push(str[i]);
}
printf("\n Reverse of a string is :- ");
for(i=top;i>=0;i--)

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 7


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

{
char t2;
t2=pop();
printf("%c",t2);
}
getch();
}

2) Polish notations :-
 The process of writing the operators of expressions either before or after their
operands is called as polish notation.
 The computer system can understand and work only on binary paradigm. It assumes
that an arithmetic operations can be take place between two operands only. For e.g.
a*b ,f+g.d/h etc.
 Usually arithmetic expression may contain more than two operators and operands. For
e.g. (a+b)*c*(d/e). This type of complex arithmetic expressions can be converted into
polish strings using stack.
 There are basically 3 types of notations
a) Infix expression
b) Prefix expression
c) Postfix expression
a) Infix expression :- X+Y
Operators are written in-between their operands. This is the usual way we write
expressions. An expression such as A * ( B + C ) / D is usually taken to mean
something like: "First add B and C together, then multiply the result by A, then divide
by D to give the final answer."

b) Prefix expression :- +XY


If the operator symbols are placed before its operands then the expression is called as
prefix expression. For e.g. +XY
As the operator ‘+’ is placed before the operands X & Y this notation is called as
prefix notation.

c) Postfix notation :-XY+


If the operator symbols are placed after its operands , then the expression is called as
postfix notation. For e .g. XY+
As the operator ‘+’ is placed after the operands X & Y this notation is called as
postfix notation.

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 8


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Infix expression Prefix expression Postfix expression

A+B +AB AB+


(A-C)*D *-ACD AC-D*
(A+B)/(C-D) /+AB-CD AB+CD-/
A+(C*D) +A*CD ACD*+

Operator precedence :-

Operator Symbol Precedence

Exponential $ Highest
Multiplication / Division *, / Middle
Addition / Subtraction +,- Lowest

3) Recursion :-
Recursion is process of expressing functions in terms of itself. We can also define a
recursion is a process in which function calls itself with reduced input & has base
condition to stop i.e. the recursive function must satisfy two conditions
a) It must have termination condition
b) After each recursive call it should reach a value nearing to terminal condition.

For e.g. To find factorial of number


We know that
fact (n)=1 if n=0
n*fact(n-1) otherwise
suppose we want to calculate 5! , so we can calculate it as
5!=5*4!
4!=4*3!
3!=3*2!
2!=2*1!
1!=1*0!
0!=1

Now 5! Can be calculated as


0!=1
1!=1*0!=1*1=1
2!=2*1!=2*1=2
3!=3*2!=3*2=6
4!=4*3!=4*6=24
5!=5*4!=5*24=120
In this way we can calculate factorial of any number.

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 9


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Program for factorial of number using recursion :-

#include<stdio.h>
#include<conio.h>
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
void main()
{
int n;
clrscr();
printf("\n Enter the number ");
scanf("%d",&n);
printf("\n Factorial of %d = %d",n,fact(n));
getch();
}

Output :-
Enter the number 5
Factorial of 5 = 120

‘C’ program for multiplication of natural numbers using recursion.

#include<stdio.h>
#include<conio.h>
int multiply(int,int);
void main()
{
int a,b,product;
printf("\n Enter any two integers: ");
scanf("%d%d",&a,&b);
product = multiply(a,b);
printf("\n Multiplication of two integers is %d",product);
getch();
}
int multiply(int a,int b)
{
static int product=0,i=0;
if(i < a)
{
product = product + b;
i++;
multiply(a,b);
}
return product;
}

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 10


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Output :-

Enter any two integers:4 5


Multiplication of two integers is 20

Program for Fibonacci series using recursion :-

#include<stdio.h>
#include<conio.h>
int Fibonacci(int);
void main()
{
int n, i = 0, c;
printf("\n Enter the last position for series ");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
getch();
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

Output :-

Enter the last position for series 8


Fibonacci series
0
1
1
2
3
5
8
13

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 11


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Advantages & disadvantages of recursion :-


Advantage
1) Usually simple
2) The recursion is very flexible in data structure like stacks, queues, linked list and quick
sort.
3) Using recursion, the length of the program can be reduced.
4) Avoidance of unnecessary calling of functions
Disadvantage
1) It requires extra storage space. The recursive calls and automatic variables are stored on
the stack.
2) The recursion function is not efficient in execution speed and time.
3) A recursive function is often confusing.
4) The exit point must be explicitly coded.
5) It is difficult to trace the logic of the function.

2) Conversion of infix expression to postfix expression :-

While evaluating an infix expression to postfix expression , there is an


evaluation order according to which the operations are executed
o Brackets or parenthesis
o Exponents
o Multiplication / division
o Addition / subtraction
The operators with the same priority like + or _ are evaluated from left to right.

Algorithm for conversion of infix expression to postfix expression :-


1) Start
2) Initialize an empty stack and postfix string
3) Read the tokens from infix string one at a time from left to right
4) If the token is an operand , add it to postfix string
5) If the token is left parenthesis , push it on to stack
6) If the token is right parenthesis
o Repeatedly pop the stack and add the popped elements into the postfix string
until a left parenthesis is encountered
o Remove the left parenthesis from the stack and ignore it
7) If the token is operator
o If the stack is empty push the operator onto the stack.
o If stack is not empty compare the precedence of operator with the element on
top of stack
 If the operator in the stack has higher precedence than the token ,pop
the stack element and add it to the postfix string else push the operator
onto the stack
 Repeat this step until stack is not empty or the operator in the stack has
higher precedence than the token

8) Repeat this process till all the characters are read

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 12


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

9) After all the characters are read and the stack is not empty then pop the stack and add
the popped elements to postfix string
10) Stop

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

SR.NO SCANNED STACK POSTFIX STRING


TOKEN
1 ( (
2 A ( A
3 + (+ A
4 B (+ AB
5 * (+* AB
6 C (+* ABC
7 - (+ ABC*
8 ( ABC*+
9 (- ABC*+
10 D (- ABC*+D
11 ) ABC*+D-
12 / / ABC*+D-
13 ( /( ABC*+D–
14 E /( ABC*+D–E
15 * /(* ABC*+D–E
16 F /(* ABC*+D–EF
17 ) ABC*+D–EF*/

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

SR.NO SCANNED STACK POSTFIX STRING


TOKEN
1 ( (
2 A ( A
3 * (* A
4 B (* AB
5 + (+ AB*
6 C (+ AB*C
7 / (+/ AB*C
8 D (+/ AB*CD
9 ) AB*CD/+
10 * * AB*CD/+
11 ( *( AB*CD/+
12 E *( AB*CD/+E
13 + *(+ AB*CD/+E
14 F *(+ AB*CD/+EF
15 $ *(+$ AB*CD/+EF
16 G *(+$ AB*CD/+EFG
17 ) AB*CD/+EFG$+*

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 13


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Example 3 :- A $ B * C – D + E / F / (G + H)

SR.NO SCANNED STACK POSTFIX STRING


TOKEN
1 A A
2 $ $ A
3 B $ AB
4 * * AB$
5 C * AB$C
6 - - AB$C*
7 D - AB$C*D
8 + + AB$C*D-
9 E + AB$C*D-E
10 / +/ AB$C*D-E
11 F +/ AB$C*D–EF
12 / +// AB$C*D–EF
13 ( +//( AB$C*D–EF
14 G +//( AB$C*D–EFG
15 + +//(+ AB$C*D–EFG
16 H +//(+ AB$C*D–EFGH
17 ) A B $ C * D – E F G H+ / / +

Example 4 :- ( A + ( B * C ) ) / ( C – (D * B ) )

SR.NO SCANNED STACK POSTFIX STRING


TOKEN
1 ( (
2 A ( A
3 + (+ A
4 ( (+( A
5 B (+( AB
6 * (+(* AB
7 C (+(* ABC
8 ) (+ A B C*
9 ) A B C* +
10 / / A B C* +
11 ( /( A B C* +
12 C /( A B C* + C
13 - /(- ABC*+C
14 ( /(-( ABC*+C
15 D /(-( A B C* + C D
16 * /(-(* A B C* + C D
17 B /(-(* ABC*+CDB
18 ) /(- A B C* + C D B *
19 ) ABC*+CDB*-/

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 14


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Program for conversion of infix expression to postfix expression :-

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#define BLANK ' '
#define TAB '\t'
#define MAX 50

void push(long int symbol);


long int pop();
void infix_to_postfix();
int priority(char symbol);
int isEmpty();
int white_space(char);

char infix[MAX], postfix[MAX];


long int stack[MAX];
int top;

int main()
{
top=-1;
printf("Enter infix : ");
gets(infix);
infix_to_postfix();
printf("Postfix : %s\n",postfix);
getch();
return 1;
}

void infix_to_postfix()
{
unsigned int i,p=0;
char next;
char symbol;
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(!white_space(symbol))
{
switch(symbol)
{
case '(':
push(symbol);
break;
case ')':
while((next=pop())!='(')
postfix[p++] = next;

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 15


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while( !isEmpty( ) && priority(stack[top])>=
priority(symbol) )
postfix[p++]=pop();
push(symbol);
break;
default: /*if an operand comes*/
postfix[p++]=symbol;
}
}
}
while(!isEmpty( ))
postfix[p++]=pop();
postfix[p]='\0'; /*End postfix with'\0' to make it a
string*/
}

/*This function returns the priority of the operator*/


int priority(char symbol)
{
switch(symbol)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default :
return 0;
}
}

void push(long int symbol)


{
if(top>MAX)
{
printf("Stack overflow\n");
exit(1);
}

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 16


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

stack[++top]=symbol;
}

long int pop()


{
if( isEmpty() )
{
printf("Stack underflow\n");
exit(1);
}
return (stack[top--]);
}
int isEmpty()
{
if(top==-1)
return 1;
else
return 0;
}

int white_space(char symbol)


{
if( symbol == BLANK || symbol == TAB )
return 1;
else
return 0;
}

long int eval_post()


{
long int a,b,temp,result;
unsigned int i;

for(i=0;i<strlen(postfix);i++)
{
if(postfix[i]<='9' && postfix[i]>='0')
push(postfix[i]-'0');
else
{
a=pop();
b=pop();
switch(postfix[i])
{
case '+':
temp=b+a; break;
case '-':
temp=b-a;break;
case '*':
temp=b*a;break;
case '/':
temp=b/a;break;

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 17


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

case '%':
temp=b%a;break;
case '^':
temp=pow(b,a);
}
push(temp);
}
}
result=pop();
return result;
}

Output :-

Enter infix : ( A + ( B * C ) ) / ( C – (D * B ) )

Postfix : A B C * + C D B * - /

3) Evaluation of postfix expression :-

 In an infix expression it is difficult for the machine to keep track of precedence of


operators , where as a postfix expression itself determines the precedence of
operators. It is easier for the machine to evaluate postfix expression than the infix
expression
 For evaluation of postfix expression we are going to use stack.
 It can processed as
o Read expression from left to right
o If the token of expression is an operand , the value of the token is pushed on to
the stack
o If the token of expression is operator , then it is required to pop required
number of operands from the stack ; then perform specific operation ,and push
the result of operation back onto the stack
o After all the tokens of the expression have been processed in this fashion, the
stack will contain a single value which is nothing but the result of postfix
expression evaluation

Algorithm for evaluation of postfix expression :-


1) Start
2) Read the expression from left to right
3) If the element is operand then
 Push the element in to the stack
4) If the element is operator then
 Pop two operands from the stack
 Evaluate the expression formed by operators & operands
 Push the result of the expression back onto the stack
5) If no more token then pop the result else go to step 3
6) Stop

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 18


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Example :-123+*4-

 Initially stack is empty . first three tokens are operands , so push them directly on
to the stack

Stack Expression

3
2
1

 Next token is “+” which is operator. So pop two operands from the top of the
stack perform addition. The first popped element will be second operand and
second popped element will be first operand for the operation.

Stack Expression

2+3=5

 The value of the expression is again pushed back into the stack

Stack Expression

5
1

 Next scanned token is “*”, which is a operator. So pop two operands from the top
of the stack perform multiplication. The first popped element will be second
operand and second popped element will be first operand for the operation.

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 19


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Stack Expression

1*5=5

 The value of the expression is again pushed back into the stack

Stack Expression

 Next token is operand 4 , so push it on the stack.

Stack Expression

4
5

 Next token is “-“, which is a operator. So pop two operands from the top of the
stack perform subtraction. The first popped element will be second operand and
second popped element will be first operand for the operation.

Stack Expression

5-4=1

 The value of the expression is again pushed back into the stack

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 20


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Stack Expression

 Since all the tokens are scanned , the remaining element in the stack will be the
result of expression.

123+*4- = 1

Program for evaluation postfix expression :-

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 50
int stack[MAX];
char post[MAX];
int top=-1;
void pushstack(int tmp);
void calculator(char c);
void main()
{
int i;
clrscr();
printf("Insert a postfix notation :: ");
gets(post);
for(i=0;i<strlen(post);i++)
{
if(post[i]>='0' && post[i]<='9')
{
pushstack(i);
}
if(post[i]=='+' || post[i]=='-' || post[i]=='*' ||
post[i]=='/' || post[i]=='^')
{
calculator(post[i]);
}
}
printf("\n\n Result :: %d",stack[top]);
getch();
}
void pushstack(int tmp)
{
top++;
stack[top]=(int)(post[tmp]-48);

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 21


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

}
void calculator(char c)
{
int a,b,ans;
a=stack[top];
stack[top]='\0';
top--;
b=stack[top];
stack[top]='\0';
top--;
switch(c)
{
case '+':
ans=b+a;
break;
case '-':
ans=b-a;
break;
case '*':
ans=b*a;
break;
case '/':
ans=b/a;
break;
case '^':
ans=b^a;
break;
default:
ans=0;
}
top++;
stack[top]=ans;
}

Output :-
Insert a postfix notation ::123+*4-

Result ::1

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 22


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Example 1 :- 6 2 3 + - 3 8 2 / + * 2 $ 3 +

Sr.no Token Operand 1 Operand 2 value Stack


scan
1 6 6
2 2 6,2
3 3 6,2,3
4 + 2 3 5 6,5
5 - 6 5 1 1
6 3 1,3
7 8 1,3,8
8 2 1,3,8,2
9 / 8 2 4 1,3,4
10 + 3 4 7 1,7
11 * 1 7 7 7
12 2 7,2
13 $ 7 2 49 49
14 3 49,3
15 + 49 3 52 52
6 2 3 + - 3 8 2 / + * 2 $ 3 + = 52

Example 2 :- 5 6 2 + * 12 4 / -

Sr.no Token Operand 1 Operand 2 value Stack


scan
1 5 5
2 6 5,6
3 2 5,6,2
4 + 6 2 8 5,8
5 * 5 8 40 40
6 12 40,12
7 4 40,12,4
8 / 12 4 3 40,3
9 - 40 3 37 37
5 6 2 + * 12 4 / - = 37

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 23


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Example 3 :- 4 2 $ 3 * 3 – 8 4 / 1 1 + / +

Sr.no Token Operand 1 Operand 2 value Stack


scan
1 4 4
2 2 4,2
3 $ 4 2 16 16
4 3 16,3
5 * 16 3 48 48
6 3 48,3
7 - 48 3 45 45
8 8 45,8
9 4 45,8,4
10 / 8 4 2 45,2
11 1 45,2,1
12 1 45,2,1,1
13 + 1 1 2 45,2,2
14 / 2 2 1 45,1
15 + 45 1 46 46

4 2 $ 3 * 3 – 8 4 / 1 1 + / + = 46

6) Conversion of infix expression to prefix expression :-

Prefix notation places each operator before its operands. Steps for conversion of infix to
prefix expression are:-
 Parenthesize the infix expression according to priority
 Move each operator to its corresponding left parenthesis
 Remove the parenthesis

For example :- (A+B)/(C-D)


Parenthesize the expression
((A+B)/(C–D))
Move each operator to its corresponding left parenthesis

( ( A + B ) / ( C – D ) )

Arrows indicates where to place the operator

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 24


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Remove the parenthesis


/+AB–CD

Algorithm for conversion of infix expression to prefix expression :-


1) Start
2) Initialize an empty stack and prefix string
3) Read the tokens from infix string one at a time from right to left
4) If the token is an operand , add it to prefix string
5) If the token is right parenthesis , push it on to stack
6) If the token is left parenthesis
o Repeatedly pop the stack and add the popped elements into the prefix string
until a right parenthesis is encountered
o Remove the right parenthesis from the stack and ignore it
7) If the token is operator
o If the stack is empty push the operator onto the stack.
o If stack is not empty compare the precedence of operator with the element on
top of stack
 If the operator in the stack has higher precedence than the token ,pop
the stack element and add it to the prefix string else push the operator
onto the stack
 Repeat this step until stack is not empty or the operator in the stack has
higher precedence than the token

8) Repeat this process till all the tokens are read


9) After all the characters are read and the stack is not empty then pop the stack and add
the popped elements to prefix string
10) Stop

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

SR.NO SCANNED STACK PREFIX STRING


TOKEN
1 ) )
2 G ) G
3 + )+ GG
4 ( / +GG
5 / / +GG
6 F // F+GG
7 / // F+GG
8 E E F+GG
9 + + / / E F+GG
10 D + D/ / E F+GG
11 - +- D/ / E F+GG
12 C +- C D/ / E F+GG
13 * +-* C D/ / E F+GG
14 B +-* B C D/ / E F+GG
15 $ +-*$ B C D/ / E F+GG
16 A +-*$ A B C D/ / E F+GG
17 + - * $A B C D/ / E F+GG

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 25


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Example 2 :- ( ( A + B ) * ( C – D ) )

SR.NO SCANNED STACK PREFIX STRING


TOKEN
1 ) )
2 ) ))
3 D )) D
4 - ))- D
5 C ))- CD
6 ( ) -C D
7 * )* -C D
8 ) )*) -C D
9 B )*) B-C D
10 + )*)+ B-C D
11 A )*)+ A B-C D
12 ( )* + A B-C D
13 ( * +A B-C D

Example 3 :- ( A – B / C ) * ( D *E – F )

SR.NO SCANNED STACK PREFIX STRING


TOKEN
1 ) )
2 F ) F
3 - )- F
4 E )- EF
5 * )-* EF
6 D )-* DEF
7 ( -*DEF
8 * * -*DEF
9 ) *) -*DEF
10 C *) C-*DEF
11 / *)/ C-*DEF
12 B *)/ BC-*DEF
13 - *)- /BC-*DEF
14 A *)- A/ B C - * D E F
15 ( -A/ B C - * D E F
16 * -A/ B C - * D E F
17

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 26


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Example 4 :- ( A + ( B * C ) ) / ( C – ( D * B ) )

SR.NO SCANNED STACK PREFIX STRING


TOKEN
1 ) )
2 ) ))
3 B )) B
4 * ))* B
5 D ))* DB
6 ( ) * DB
7 - )- * DB
8 C )- C* DB
9 ( -C* DB
10 / / -C* DB
11 ) /) -C* DB
12 ) /)) -C* DB
13 C /)) C -C* DB
14 * /))* C -C* DB
15 B /))* B C -C* DB
16 ( /) * B C -C* DB
17 + /)+ * B C -C* DB
18 A /)+ A* B C -C* DB
19 ( / +A* B C –C* DB
20 /+A* B C –C* DB

Program for conversion of infix expression to prefix expression :-

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20

char stack[MAX];
int top = -1;
char pop();
void push(char item);

int prcd(char symbol)


{
switch(symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '^':
case '$':
return 6;
case '(':

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 27


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

case ')':
case '#':
return 1;
}
}

int isoperator(char symbol) {


switch(symbol) {
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
default:
return 0;
}
}

void convertip(char infix[],char prefix[]) {


int i,symbol,j=0;
char test[MAX];

infix=strrev(infix);
stack[++top]='#';

for(i=0;i<strlen(infix);i++) {
symbol=infix[i];
if(isoperator(symbol)==0) {
prefix[j]=symbol;
j++;
}else {
if(symbol==')') {
push(symbol);
}else if(symbol=='(') {
while(stack[top]!=')') {
prefix[j]=pop();
j++;
}
pop();//pop out (.
}else {
if(prcd(symbol)>prcd(stack[top])) {
push(symbol);
}else {
while(prcd(symbol)<=prcd(stack[top])) {
prefix[j]=pop();
j++;
}
push(symbol);
}//end of else.
}//end of else.
}//end of else.
}//end of for.

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 28


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

while(stack[top]!='#') {
prefix[j]=pop();
j++;
}
prefix[j]='\0';//null terminate string.
prefix=strrev(prefix);
}

int main() {
char infix[20],prefix[20];
clrscr();
printf("Enter the valid infix string:\n");
gets(infix);
convertip(infix,prefix);
printf("The corresponding prefix string is:\n");
puts(prefix);
getch();
return 0;
}

void push(char item) {


top++;
stack[top]=item;
}

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

Output :-
Enter the valid infix string: ( ( A + B ) * ( C – D ) )

The corresponding prefix string is: * +A B-C D

7) Evaluation of prefix expression :-


 In an infix expression it is difficult for the machine to keep track of precedence of
operators, where as a prefix expression itself determines the precedence of operators.
It is easier for the machine to evaluate prefix expression than the infix expression
 For evaluation of prefix expression we are going to use stack.
 It can processed as
o Read expression from right to left
o If the token of expression is an operand , the value of the token is pushed on to
the stack
o If the token of expression is operator , then it is required to pop required
number of operands from the stack ; then perform specific operation ,and push
the result of operation back onto the stack
o After all the tokens of the expression have been processed in this fashion, the
stack will contain a single value which is nothing but the result of prefix
expression evaluation

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 29


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Algorithm for evaluation of postfix expression :-


1) Start
2) Read the expression from right to left
3) If the element is operand then
 Push the element in to the stack
4) If the element is operator then
 Pop two operands from the stack
 Evaluate the expression formed by operators & operands
 Push the result of the expression back onto the stack
5) If no more token then pop the result else go to step 3
6) Stop

Example :- + 2 * 3 + 4 5

 Initially stack is empty. Scan from right to left .First two tokens are operands , so
push them directly on to the stack

Stack Expression

4
5

 Next token is “+” which is operator. So pop two operands from the top of the
stack perform addition. The first popped element will be first operand and second
popped element will be second operand for the operation.

Stack Expression

4+5=9

 The value of the expression is again pushed back into the stack

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 30


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Stack Expression

 Next token is 3 which operand. so push it onto stack.



Stack Expression

3
9

 Next scanned token is “*”, which is a operator. So pop two operands from the top
of the stack perform multiplication. The first popped element will be first operand
and second popped element will be second operand for the operation.

Stack Expression

3*9=27

 The value of the expression is again pushed back into the stack

Stack Expression

27

 Next token is operand 2 , so push it on the stack.

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 31


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Stack Expression

2
27

 Next token is “+“, which is a operator. So pop two operands from the top of the
stack perform subtraction. The first popped element will be first operand and
second popped element will be second operand for the operation.

Stack Expression

2+27=29

 The value of the expression is again pushed back into the stack

Stack Expression

29

 Since all the tokens are scanned, the remaining element in the stack will be the
result of expression.

+ 2 * 3 + 4 5 = 29

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 32


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Example 1 :- + - * + 1 2 / 4 2 1 $ 4 2

Sr.no Token Operand 1 Operand 2 value Stack


scan
1 2 2
2 4 2,4
3 $ 4 2 16 16
4 1 16 ,1
5 2 16,1,2
6 4 16,1,2,4
7 / 4 2 2 16,1,2
8 2 16,1,2,2
9 1 16,1,2,2,1
10 + 1 2 3 16,1,2,3
11 * 3 2 6 16,1,6
12 - 6 1 5 16,5
13 + 5 16 21 21

+ - * + 1 2 / 4 2 1 $ 4 2=21

Example 2 :- + - 2 7 * 8 / 12 4

Sr.no Token Operand 1 Operand 2 value Stack


scan
1 4 4
2 12 4,12
3 / 12 4 3 3
4 8 3,8
5 * 8 3 24 24
6 7 24,7
7 2 24,7,2
8 - 2 7 -5 24,-5
9 + -5 24 19 19

+ - 2 7 * 8 / 12 4 = 19

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 33


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

Program for prefix expression evaluation :-

#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<math.h>
#define Max 20
int st[Max], top=-1;

void push(int ch)


{
if (top == Max-1)
{
printf("Stack is full\n");
}
else
{
top++;
st[top]=ch;
}
}

int pop()
{
int ch;
if (top==-1)
{
printf("Stack is empty\n");
}
else
{
ch=st[top];
top--;
}
return ch;
}

void dispstack()
{
int k;
printf("stack Content: ");
for (k=top; k>=0; k--)
{
printf("%d, ", st[k]);
}
printf("\n");
}

int PreEval(char s[25])


{

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 34


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

char temp[25];
int i,val=0,ch1,ch2,j=0;
i=0; top=-1;
while (s[i]!='\0')
{
/*if operand is countered print it*/
if ( (s[i]>=48 && s[i]<=57) )
{
j=0;
temp[j]=s[i];
j++;
temp[j]='\0';
push(atoi(temp));
}
else
{
ch2=pop();
ch1=pop();
switch(s[i])
{
case '+' :
val=ch2+ch1;
break;

case '-' :
val=ch2-ch1;
break;

case '*' :
val=ch2*ch1;
break;

case '/' :
val=ch2/ch1;

break;

case '^' :
val=pow(ch2,ch1);
break;
}
push(val);
}
i++;
}
val=pop();
return val;
}

void main()
{
char s[25],s1[25];
int val;

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 35


Course : Data Structures Using ‘C’ 3.Stack Course Code:22317

clrscr();
printf("\n Enter a Prefix expression for evaluation\n");
scanf("%s",s);
strcpy(s1,strrev(s));
val= PreEval(s1);
printf("\n Value of Prefix Expression=%d\n", val);
getch();
}

Output :-

Enter a Prefix expression for evaluation


+-*+12/421$42
Value of Prefix Expression=21

Course Co-Ordinator :Mrs. Kshirsagar Sayali R. Page 36

You might also like