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

DS Stack and its Applications (1) (1)

The document provides an overview of data structures, specifically focusing on stacks, which are linear data structures that operate on a Last-In-First-Out (LIFO) principle. It details the operations associated with stacks, such as push, pop, and checks for fullness and emptiness, along with examples and applications including the evaluation of postfix expressions and conversion from infix to postfix expressions. Additionally, it includes code implementations for stack operations and expression evaluations.

Uploaded by

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

DS Stack and its Applications (1) (1)

The document provides an overview of data structures, specifically focusing on stacks, which are linear data structures that operate on a Last-In-First-Out (LIFO) principle. It details the operations associated with stacks, such as push, pop, and checks for fullness and emptiness, along with examples and applications including the evaluation of postfix expressions and conversion from infix to postfix expressions. Additionally, it includes code implementations for stack operations and expression evaluations.

Uploaded by

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

Data: The Data is nothing but meaning full information or facts.

Structure: The Structure is nothing but bundle of different data types.


Definition: Data structure is a collection of data elements organized in specific manner and
functions are defined to store and retrieve the data.
The data structure mainly classified into
1. Linear data structure.
2. Non-linear data structure.
1. Linear data structure: It is continuous.
Ex: Stacks, Queues, Linked lists.

Fig 1.1 Linear Data Structures


2. Non-Linear data Structure: It is discrete.
Ex: Trees and Graphs.
Stack:
Stack: It is linear data structure. In stack, insertion and deletion is done only one end,
that end is called as top of the Stack and insertion is called as “Push( )” and deletion
is called as “Pop( )”. In Stack, the last inserted element will come out first. Because
of this it is called as Last-In-First-Out (LIFO).
Operations on stack:
a. create(s): It is used to create the empty stack(s). Initially top is set to ‘-1’.

Size=5
4

0
top = -1

b. push(s, x): It is used to push the data element ‘x’ into the stack ‘s’. Whenever we
are pushing the data element into the stack first we check the condition. if
(top==size-1), if it is true indicate stack is full or overflow. Otherwise, Increment
the top and insert the data element in that location. This is shown in below.

Push(s,2) Push(s,4) Push(s,6) Push(s,8) Push(s,10)

4 4 4 4 4
10

8 8
3 3 3 3 3
6 6 6
2 2 2 2 2
4 4 4 4
1 1 1 1 1
2 2 2 2 2
0 0 0 0 0
top = 0 top = 1 top = 2 top = 3 top = 4

top top+1

After inserting 5 elements the top reaches the size-1. Therefore no more insertion is possible
because and the stack is full.
c. pop(s): It is used to delete the data element from the stack. Here also we check
the condition if(top==-1). If it is true the stack is empty or underflow. Otherwise
retrieve the data element from the top of the stack and store it in temporary
variable ‘x’ and then top will be decremented by 1. This is shown in below.

pop(s) pop(s) pop(s) pop(s) pop(s)

4 4 4 4 4
8
3 3 3 3 3
6 6
2 2 2 2 2
4 4 4
1 1 1 1 1
2 2 2 2
0 0 0 0 0
top = 3 top = 2 top = 1 top = 0 top =-1

x=10 x=8 x=6 x=4 x=2

top top-1

After deleting the 5 elements the top reaches the ‘-1’ that means that the stack is empty.

d. isfull(): It is used to check whether the stack is full or not while checking the
condition if(top==size-1). If it is true, the stack is full.
e. isempty(): It is used to check whether the stack is empty or not while checking
the condition if(top==-1). If it is true, the stack is empty
Ex: The collection of books or plates placed on one on another is nothing but the stack.
Applications:
1. Evolution of postfix expression.
2. Conversion from Infix to Postfix.
3. Stack is used in Recursion.
Stack is implemented by using two ways:
i. By using Arrays.
ii. By using Linked lists.
/* Implementation of Stack by using arrays*/
#include <stdio.h>
#include<process.h>
#define size 5
struct stack
{
int top;
int item[size];
};
struct stack s;
void push(struct stack *ps,int x);
int pop(struct stack *ps);
void display(struct stack *ps);
void main()
{
int ele,ch;
s.top=-1;
clrscr();
do
{
printf("\n 1: push \n");
printf(" 2: pop \n");
printf(" 3: display \n");
printf(" 4: exit \n");
printf("enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\n ele:");
scanf("%d",&ele);
push(&s,ele);
break;
case 2:ele=pop(&s);
if(ele!=0)
printf("deleted ele is %d",ele);
break;
case 3:display(&s);
break;
case 4:exit(0);
}
}while(ch<4);
getch();
}
void push(struct stack *ps,int x)
{
if (ps->top==size-1)
printf("stack is full\n");
else
{
ps->top=ps->top+1;
ps->item[ps->top]=x;
printf("\n ele inserted into stack");
}
}
int pop(struct stack *ps)
{
int y;
if (ps->top==-1)
{
printf("stack under flow\n");
return 0;
}
else
{
y=ps->item[ps->top];
ps->top=ps->top-1;
return y;
}
}
void display(struct stack *ps)
{
int i;
if(ps->top==-1)
printf("stack is empty\n");
else
{
printf("\nthe elements in the stack are:");
for(i=ps->top;i>=0;i--)
printf("%4d",ps->item[i]);
}
}
OUTPUT:
Applications of Stack:
Generally, the Mathematical Expression is represented in the following Expressions.
1. Infix Expression
2. Prefix Expression
3. Postfix Expression
Infix Expression: The operator is placed between the two operands. Such an expression
is called as Infix Expression.
Ex: A+B, A*B.
Prefix Expression: The operator is placed before two operands. Such an expression is
called as Prefix Expression.
Ex: +AB,*AB
Postfix Expression: The operator is placed after the two operands. Such an expression is
called as Postfix Expression.
Ex: AB+, AB*
Generally, the Mathematical Equation consists of four operators.
Multiplication (*)
Division (/)
Addition (+)
Subtraction (-)
And also consists of fifth operator i.,e Exponential ($ or ^) Ex: 3$2=9
The preceding of operators from highest to lowest:
Exponential ($ or ^)
Multiplication (*) or Division (/)
Addition (+) or Subtraction (-)
To avoid the confusion we use the parenthesis i.,e ( ).

Table 1.1 Conversions from Infix Expression to Prefix and Postfix Expression
I. Evaluation of Postfix Expression:
Ex: Evaluate the given Postfix Expression.
345*+
Sol: The given expression is evaluated from left to right one symbol at a time if it is the
operand directly push it into the stack, if it is operator pop top two operands from the
stack and apply operator between operand2 and operand 1 and get the result and then
push the result into the stack. This is continued until given expression is completed. If
input string is completed pop the result from the stack and display it on the screen.

Symbol Operand 1 Operand2 Result Stack

3 3

4 3,4

5 3,4,5

* 5 4 20 3,20

+ 20 3 23 23

e.o.i ---- ----- ---

The final Out put: 23


Table 1.2 Evaluation of Postfix Expression
Ex2: Evaluate the Postfix Expression 9 8 + 3 8 2 / * 2 + -

Symbol Operand 1 Operand2 Result Stack

9 9

8 9,8

+ 8 9 17 17

3 17,3

8 17,3,8

2 17,3,8,2

/ 2 8 4 17,3,4

* 4 3 12 17,12

2 17,12,2

+ 2 12 14 17,14

- 14 17 3 3

The final Out put: 3


Ex3:6 2 3 + - 3 8 2 / + * 2 $ 3 + Evaluate the given postfix expression?

Symbol Operand 1 Operand2 Result Stack

6 6

2 6,2

3 6,2,3

+ 3 2 5 6,5

- 5 6 1 1

3 1,3

8 1,3,8

2 1,3,8,2

/ 2 8 4 1,3,4

+ 4 3 7 1,7

* 7 1 7 7

2 7,2

$ 2 7 49 49

3 49,3

+ 3 49 52

Result:52
Algorithm for Evaluation of Postfix Expression:

Step 1: Create empty stack.


Step 2: Evaluate the given Expression from left to right and one symbol at a
time.
Step 3: while (not end of input)
{
if(the symbol is operand)
push(stack, symbol);
else if(symbol is operator)
{
op1=pop( );
op2=pop( );
result=op2 symbol op1;
push(stack, result);
}
}
Pop( ) the result from the stack and display it on the screen.
/* Implementation of Evaluation of Postfix Expression*/
#include<stdio.h>
#include<math.h>
struct stack
{
int item[10];
int top;
};
struct stack s;
void push(struct stack *ps,int x);
int pop(struct stack *ps);
int evl(char post[]);
void main()
{
char exp[10];
int res;
s.top=-1;
printf("\n enter postfix expression:");
gets(exp);
res=evl(exp);
printf("\n res=%d",res);
}
int evl(char post[])
{
int i,r,op1,op2,y,k;
char c;
for(i=0;post[i]!='\0';i++)
{
c=post[i];
if((c=='+')||(c=='-')||(c=='*')||(c=='/')||(c=='$'))
{
op1=pop(&s);
op2=pop(&s);
r=oper(c,op2,op1);
push(&s,r);
}
else
{
printf("\n value for operand:");
scanf("%d",&y);
push(&s,y);
}
}
k=pop(&s);
return k;
}
int oper(char c,int a,int b)
{
switch(c)
{
case '+':return (a+b);
case '-':return (a-b);
case '*':return (a*b);
case '/':return (a/b);
case '$':return pow(a,b);
}
}
void push(struct stack *ps,int x)
{
ps->top=ps->top+1;
ps->item[ps->top]=x;
}
int pop(struct stack *ps)
{
int a;
a=ps->item[ps->top];
ps->top=ps->top-1;
return a;
}

OUTPUT:

II. Conversion from Infix Expression to Postfix Expression:

Ex1: Consider the Infix Expression A+B*C and convert it into Postfix Expression.

Sol: The given Expression is evaluated from left to right. If it is operand directly send to
postfix Expression. If it is operator push it into the stack until the right movement. If the
input string is completed pop the elements from the stack until the stack is empty and
popped elements are send to Postfix Expression.

Symbol Stack Postfix Expression

A A

+ + A

B + AB

* +* AB

C +* ABC

e.o.i empty ABC*+

Table 1.3Conversion from Infix Expression to Postfix Expression

Verification: A+B*C
A+BC*
ABC*+
Ex2: Consider the Infix Expression A*B+C and convert it into Postfix Expression.

Sol: if in stack priority of top is greater than or equal to in coming priority of symbol then
pop the elements from the stack and poped elements are send to postfix expression and
then push the upcoming symbol.

Symbol Stack Postfix Expression

A A

* * A

B * AB

+ + AB*

C + AB*C

e.o.i empty A B *C+

Verification: A*B+C
AB*+C
AB*+
Ex3: Consider the Infix Expression (A+B)*C and convert it into Postfix Expression.

Sol: If it is the left parenthesis directly push it into the stack if is the right parenthesis then
pop the elements from the stack until left parenthesis is found and poped elements are send
to postfix expression and then discard the left and right parenthesis.

Symbol Stack Postfix Expression

( (

A A

+ (+ A

B (+ AB

) AB+

* * AB+

C * AB+C

eof empty AB+C*

Verification: (A+B)*C
AB+ * C
AB+C*
Algorithm for conversion of Infix Expression to Postfix Expression:
Step1: Create empty stack.
Step2: while(not end of input)
{
Symbol=next input character
if(symbol is operand)
Send to Postfix Expression
else if(symbol = ‘(‘ )
push(stack, symbol)
else if(symbol=’)’)
{
Pop the elements from the stack until left parenthesis is found and
popped elements are send to postfix expression and also delete left
and right parenthesis.
}
else if(symbol is operator)
{
if (isp(top)>=icp(symbol))
Pop the elements from the stack and popped elements are send to
postfix expression.
push (stack,symbol)
}
}
Pop the elements from the stack until stack is empty and popped elements
are
send to postfix Expression.

OUTPUT:

/*Implementation to Convert Infix Expression to Postfix


Expression*/

#include<stdio.h>

struct stack

char item[10];

int top;

};

struct stack s;

void con(char infix[],char postfix[]);

void push(struct stack *ps,char x);

char pop(struct stack *ps);


int isp(char x);

int icp(char x);

void main()

char infix[10],postfix[10];

s.top=-1;

printf("\n infix exp:");

gets(infix);

con(infix,postfix);

printf("\n postfix exp:");

puts(postfix);

void con(char infix[],char postfix[])

int i,j=0;

char b,c;

push(&s,'#');

for(i=0;infix[i]!='\0';i++)

c=infix[i];

if(c=='(')

push(&s,c);

else if(c>='A'&&c<='Z')

postfix[j++]=c;

else if((c=='+')||(c=='-
')||(c=='*')||(c=='/')||(c=='*')||(c=='$'))

while(isp(s.item[s.top])>=icp(c))

postfix[j++]=pop(&s);

push(&s,c);
}

else if(c==')')

while((b=pop(&s))!='(')

postfix[j++]=b;

}//end of for

b=pop(&s);

while(b!='#')

postfix[j++]=b;

b=pop(&s);

postfix[j]='\0';

int isp(char x)

switch(x)

case '$':return 4;

case '*':return 3;

case '/':return 3;

case '+':return 2;

case '-':return 2;

case '(':return 1;

case '#':return 0;

}
int icp(char x)

switch(x)

case '$':return 4;

case '*':return 3;

case '/':return 3;

case '+':return 2;

case '-':return 2;

void push(struct stack *ps,char x)

ps->top=ps->top+1;

ps->item[ps->top]=x;

char pop(struct stack *ps)

char y;

y=ps->item[ps->top];

ps->top=ps->top-1;

return y;

OUTPUT:
III. Recursion: The function calling itself is called as recursion. The recursion is
implemented by using Stack.
Ex: The recursive function for finding the Factorial of a given number.
Algorithm to find the factorial of a given number
Step1:Factorial of given number is calculated by using formula
fact(n)=n*(n-1)*(n-2)*………….1 , if n>0
Step2:if( n==0) ,then
return 1;
/* Recursive function for factorial of a given
number */
#include<stdio.h>
int fact(int);
void main()
{
int n,f;
printf("\n enter n");
scanf("%d",&n);
f=fact(n);
printf("fact of %d is %d",n,f);
}
int fact(int n)
{
int x;
if(n==0)
return 1;
x=n-1;
return (n*fact(x));
}
OUTPUT:
Table 1.4 Factorial Evaluation using Stack
Ex: The recursive function for Multiplication of Two Natural Numbers.
Algorithm for Multiplication of Two Natural Numbers.
Step1: Multiplication of Two Natural Numbers are calculated by using the
formula a*b=a*(b-1) + a, if b>1
Step2:if( b==1) then
return a;
//Recursive function for Multiplication of Two Natural Numbers.
#include<stdio.h>
void main()
{
int a,b,t;
clrscr();
printf("\n a and b");
scanf("%d%d",&a,&b);
t=mul(a,b);
printf("\n mul two natural numbers=%d",t);
}
int mul(int a,int b)
{
int c;
if(b==1)
return a;
c=b-1;
return (mul(a,c)+a);
}
Output:
Ex: The recursive function for Greatest Common Divisor of Two numbers
Algorithm for GCD(m,n)
Step1:if(n>m) then
Return GCD(n,m)
Step2:if( n==0) then
return m;
otherwise
return GCD(n,mod(m,n));

//Recursive function for Greatest Common Divisor


#include<stdio.h>
int gcd(int,int);
void main()
{
int m,n,f;
printf("\n enter m and n");
scanf("%d %d",&m,&n);
f=gcd(m,n);
printf("\n gcd= is %d",f);
}
int gcd(int m,int n)
{
int x;
if(n>m)
return gcd(n,m);
else if(n==0)
return m;
x=m%n;
return gcd(n,x);
}
Output:
Ex: The Recursive function for reverse of a given number

Step1:Get the number from the user


Step2: if (number) then
Perform modulation get remainder and store it in Static variable
and then apply division.

// Recursive function for reverse of a given number


#include<stdio.h>
void main()
{
int n,r;
printf("\n num:");
scanf("%d",&n);
r=reverse(n);
printf("\n reverse of given number=%d",r);
}
int reverse(int n)
{
static int s=0;
int r;
if(n)
{
r=n%10;
s=(s*10)+r;
reverse(n/10);
}
else
return s;
}
Out put:
Ex2: Algorithm for Recursive function Binary Search

Step1: Enter array size, array elements in sorted order and key element
Step2: Repeat Step 3 until (low<=high)
Step 3:low=0,high=n and find the mid=(low+high)/2
if(key<a[mid])
{
high=mid-1;
Search the key element low to a[mid-1];
}
else if(key>a[mid])
{
low=mid+1;
Search the key element from a[mid+1] to high;
}
else if(key==a[mid])
return (mid+1);
else
return 0;

/* Implementation of Binary Search*/


#include<stdio.h>
int binsearch(int [],int ,int,int);
void main()
{
int n,a[10],key,pos,i;
printf("size:");
scanf("%d",&n);
printf("\n array ele in sorted order:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n key:");
scanf("%d",&key);
pos=binsearch(a,key,0,n);
if(pos==0)
printf("\n ele not found");
else
{
printf("\n success");
printf("\n the key=%d found at loc=%d",key,pos);
}
}
int binsearch(int a[],int key,int l,int h)
{
int m;
if(l<=h)
{
m=(l+h)/2;
if(key<a[m])
{
h=m-1;
binsearch(a,key,l,h);
}
else if(key>a[m])
{
l=m+1;
binsearch(a,key,l,h);
}
else if(key==a[m])
return (m+1);
}
else
return 0;
}
OUTPUT:

You might also like