0% found this document useful (0 votes)
50 views14 pages

Stack New

Uploaded by

ps089827224
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)
50 views14 pages

Stack New

Uploaded by

ps089827224
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/ 14

Data Structures UNIT : STACK By : Sneha T.

Patel

 Stack:-

 A stack is an ordered collection of items into which new items may be inserted & from which items
may be deleted at one end called “top of stack”.
 Stack is a dynamic constantly changing object. Stack is also called LIFO because whichever item is
inserted last will be deleted first.
 The most and least accessible elements in a stack are known as the top and bottom of the stack
respectively.
 The new item may be put on the top of the stack or item may be removed from the top of the stack
 The above two changes which can be made to a stack are given special names when an item is added
to a stack it is pushed on the stack and when an item is removed it is popped from the stack.

D Top
C
The value is
B B Top popped & top
is decremented
A A

Push [Insertion] Pop [Deletion]

Example:-
 An example of stack is the “in” tray of a busy executive. The files pile up in the tray and
whenever the executive has time to clear the files, he/she takes it off from the top. That is, files
are added at the top and removed from the top. Therefore stacks are sometimes referred to
as LIFO Structure.
 Considered a stack of plates placed on the counter in the restaurant during the dinner time,
customers take plate from the top of the stack and waiter puts washed plate on the top of the
stack.

 There are the two method implement the stack


1) Using pointer (Linked List) (Dynamic Stack) here memory is collected dynamically and error
occurs if no more space available in memory area.
2) Using arrays (Static Stack) here fixed number is allocated at compilation time.

1) PUSH Operation:

It means to insert the elements in the stack. In executing the procedure push, one must first
test whether there is the room in stack for the new item, if not, then the condition is known as
overflow.

Algorithm:
Push (Item,n,value)
value=item to push, n=size of stack

BMU- BMCCA Page 1 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

Step-1 Set top=-1


Step-2 [Check for empty or full stack]
If (top>=n-1)
Print “Overflow/stack is full”
Return(0)
Else
Step-3 [Increment the stack pointer by one]
Top=top+1
Step-4 [Insert the value to be pushed in the stack at the location of top]
Item [top] =value
Step-5 exit

2) POP Operation:

It means to take elements from stack. In executing the procedure pop, one must first test
whether there is an element in the stack to be deleted. If not, then condition is known as
underflow.

Algorithm:

Step-1 [Check for empty]


If (top==-1)
Print “Underflow/stack is empty”
Else
Step-2 [Take out the value of the stack where pointer top is pointing]
Value=Item [top]
Step-3 [Decrement the value of top of the stack by one so as to point at the next
node to be popped]
Top=top-1
Step-4 return(value) & exit

3) PEEP Operation:

If only information store at some location in a stack is needed, then this operation can be
performed. We move logically to desired location & then fetch the information associated with
that location. To access desire elements from top of the stack is known as Peep Operation. For
example suppose we have to access 3 element from top than it is 2=c, ith=desired element=3 and
top=4.the formula is :

BMU- BMCCA Page 2 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

E
Top = top-i+1
D =4-3+1
= 1+1
C 2=C
=2
B 2=C

Algorithm:
Peep(i)

Step-1 [Check for empty]


If (top-i+1<0)
Print “not found”
Else
Step-2 [Return ith element from stack]
return(Item[top-i+1])
Step-3 Exit

4) UPDATE Operation

It is required when the content of some location in a stack is to be changed suppose


one wants to update information at the ith location in a stack than we first move the pointer to the
ith location and than input the new value of that location.

Algorithm: update(i,value)

Step-1 [Check for underflow condition]


If (top-i+1<0)
Print “Underflow/stack is empty”
Else
Step-2 [Change the element]
Item[top-i+1]=value
Step-3 Exit

BMU- BMCCA Page 3 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

Stack Application:-

There are two type of stack application.

1) Polish expression
2) Recursive
3) Stack machines, certain computers perform stack operation at the hardware or machine level.

 Polish Expression:

The process of writing the operators of an expression either before the operand or after the
operand is called Polish Notation.

When operators are written after the operands, it is called Reverse Polish Notation.

There are three types of expression:


1) Infix
2) Prefix
3) Postfix

“Pre”,”Post” &”In” refer to the relative position of the operator with respect to the two operands.

1) Infix notation:-

 In this type of expression operators are placed between the operands.


E.g.: A+ (B*C)

= a+(*BC)
=+a*bc
 In this notation the order of operations to be performed is determined by the use of
parenthesis or by the use of some operator precedence conventions.
 The levels of precedence are (highest to lowest):

Priority Operator
1 (
2 ^,$,
3 %
4 / or * (left to right)
5 + or –(left to right)
6 )

 During conversion of an infix notation we must begin with inner parenthesis and then
precede towards, the outside expression i.e. the operations with higher precedence are
converted first.

2) Prefix notation:-
BMU- BMCCA Page 4 of 14
Data Structures UNIT : STACK By : Sneha T. Patel

In this type of expression operators are placed before operands.


E.g.: +A*BC

Algorithm for converting from infix to prefix:

1. Enter the expression in infix form.


2. Reverse the expression
3. Scan its item character by character (Right to Left)
4. If the item which appears is an operand, add it to the string t (i.e. it is a temporary array of
character)
5. If the item is an operator & it is the first operator encountered, push it into the stack. If the
operand is )-closing parenthesis, push it into the stack.
6. If the operator is (- opening parenthesis, pop all the operators from the stack until we
encounter ) - closing parenthesis & add them to the string variable t. pop )-closing
parenthesis also from the stack but don’t add it to the string variable t because in prefix
form, there is no need of parenthesis display them. pop (- opening there is no need of
parentheses.
7. If the operator is the second or third operator or any operator except the first, compare the
precedence value of the current operator with the precedence current operator on the top of
the stack. If the precedence value of the current operator is higher than that of the
operator on the stack, push the current operator also onto the stack. But if the
precedence value of current operator is smaller; to the precedence value of the
operator on the stack, pop all the operators from the stack until we get the operator
on the top of the stack with precedence value lower than or equal to the precedence
value of the current operator & add these popped operators to string variable t. Then
push the current operator on the stack.
8. When expression is over, pop the entire operator from the stack & add them to the string
variable t.
9. Reverse the string array t & display it.

Example: z + (y * x - (w / v ^ u) *t) *s

Input Stack String t


S S
* * S
) *) S
T *) St
* *)* St
) *)*) St
U *)*) Stu
^ *)*)^ Stu

BMU- BMCCA Page 5 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

V *)*)^ Stuv
/ *)*)/ stuv^
w *)*)/ stuv^w
( *)* stuv^w/
- *)- stuv^w/*
X *)- stuv^w/*x
* *)-* stuv^w/*x
Y *)-* stuv^w/*xy
( * stuv^w/*xy*-
+ + stuv^w/*xy*-*
Z + stuv^w/*xy*-*z
(stack is empty) stuv^w/*xy*-*z+

Prefix notation is: +z*-*yx*/w^vuts

3) Postfix or Suffix or Reverse Polish Notation: -

In this type of expression operators are placed after the operands.


E.g.: ABC*+

Algorithm for converting from infix to postfix:

1. Enter the expression in infix form.


2. Scan its item character by character
3. If the item which appears is an operand, display it (i.e. send it to the output)
4. If the item is an operator & it is the first operator encountered, push it into the stack. If the
operand is (- opening parenthesis, push it into the stack.
5. If the operator is )-closing parenthesis, pop all the operators from the stack until we
encounter (- opening parenthesis & display them. pop (- opening there is no need of
parentheses.
6. If the operator is the second or third operator or any operator except the first, compare the
precedence value of the current operator with the precedence current operator on the top of
the stack. If the precedence value of the current operator is higher than that of the
operator on the stack, push the current operator also onto the stack. But if the
precedence value of current operator is smaller or equal to the precedence value of
the operator on the stack, pop all the operators from the stack until we get the
operator on the top of the stack with precedence value lower than the precedence
value of the current operator & display all these operators. Then push the current
7. operator on the stack.
8. When expression is over, pop the entire operator from the stack & display them.

BMU- BMCCA Page 6 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

Example: (a + b * c ^ d / e) / (f * g - h)

input Stack String t


( ( -
a ( A
+ (+ A
b (+ Ab
* (+* Ab
c (+* Abc
^ (+*^ Abc
d (+*^ Abcd
/ (+/ abcd^*
e (+/ abcd^*e
) (stack is empty) abcd^*e/+
/ / abcd^*e/+
( /( abcd^*e/+
F /( abcd^*e/+f
* /(* abcd^*e/+f
G /(* abcd^*e/+fg
- /(- abcd^*e/+fg*
H /(- abcd^*e/+fg*h
) / abcd^*e/+fg*h-
(stack is empty) abcd^*e/+fg*h-/

Postfix notation is: abcd^*e/+fg*h-/

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

1) Conversion of Expression Infix to Prefix


= (+AB)*(-CD)
= *+AB-CD

2) Conversion of Expression Infix to Postfix


= (AB+)*(CD-)
= AB+CD-*

3) Conversion of expression Postfix to Infix


AB+CD-*
= (A+B) CD-*
= (A+B) (C-D)*
BMU- BMCCA Page 7 of 14
Data Structures UNIT : STACK By : Sneha T. Patel

= (A+B)*(C-D)

4) Conversion Postfix into Prefix


1) AB+CD-*
= (+AB) CD-*
= (+AB) (-CD)*
Ans: *+AB-CD

Algorithm for converting from Postfix to Prefix:

1. If there is an operand in the expression, simply push it into stack.


2. If there is an operator in the expression, POP last two operands from the stack & insert the
operator before the two operands that were popped & again push the combination on to the
stack.
3. Repeat above two steps until expression in over.
4. The expression in the stack is in prefix form. Pop it and display it.

Example: ab+cd*-
Input Stack
A A
B a,b
+ +ab
C +ab,c
D +ab,c,d
* +ab,*cd
- -+ab*cd

Prefix notation is: -+ab*cd

 Evaluating Postfix Expression:

Example: 9 5 + 7 4 - *
Input Stack
Two values are popped;
9 9 summation is done &
pushed again in stack
5 9,5
+ 14 Two values are popped
7 14,7 from stack; subtraction
is done & result pushed
4 14,7,4 again in stack
- 14,3
Two values are popped;
* 42 multiplied & result
pushed into stack

BMU- BMCCA Page 8 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

The Result of expression is: 42

Algorithm for converting from Postfix to Infix Expression:

1. If there is an operand in the expression, simply push it into stack.


2. If there is an operator in the expression, POP last two operands from the stack & insert the
operator in between the two operands that were popped & again push the combination on to
the stack.
3. Repeat above two steps until expression in over.
4. The expression in the stack is in infix form. Pop it and display it.

Example: ab+cd-*

Input Stack
A A
B a,b
+ a+b
C a+b,c
D a+b,c,d
* a+b,c*d
- a+b-c*d

Infix notation is: a+b-c*d

 Recursion as an Application of Stack :

 A procedure that contains a procedure which calls itself is called Recursion.


OR
Function call itself called Recursion but here 1st function call 2nd function, 2nd function call 3rd
function and so on.
 Recursion is an important concept in computer science.
 Recursion is less time consuming than normal function.
 Recursion procedure must have the following 2 step.
1) There must be certain criteria that base criteria for which the procedure doesn’t call itself.
2) Each item the procedure can call itself (directly or indirectly).It must be closed to the base
criteria.
 For example, In case of factorial function each time the function call itself
& its argument is decremented by one. so the argument of the function is getting smaller so it
is nearer to the base criteria that the value of n must be 0.

Advantage of Recursion:

1. Data store in looping.


2. Recursion is a time consuming operation because of pushing all the current variables & objects
onto stack.

BMU- BMCCA Page 9 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

General Algorithm for Recursion:-

Step-1: [Preface]
Save the argument & return address.
Step-2: [Body of function]
If a base criterion is completed go to step-3.
Else perform partial computation & go to step-1.
Step-3: [Last Section]
Restore the most recently saved parameters & return address.

Example: - Algorithm of recursive factorial.

1. Give an Integer N. this algorithm find factorial N.


2. In this algorithm we will take a stack which is capital A. to store an activation record
associated with each recursive call.
3. Each activation record contains the current value of N & the current return address whenever
function is called. A copy of current argument & current address is push to the stack.
4. Whenever function completed we will fetch or pop current return address & arguments.

Algorithm:

1. [Save N & return address]


Call push(A, N, ret_add)
2. [Is the base criteria found?]
If N==0 then
Fact=1
goto step 4
Else
param=N-1
ret_add=step 3
goto step 1
3. [Calculate N!]
Fact=N*fact
4. [Restore N & ret_add]
tem_rec=pop (A) goto tem_rec

BMU- BMCCA Page 10 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

Recursive Process: (show algorithm above for this flowchart)

Start

Preface
Local variables save
formal parameters
return address value on
stack

Intermediate Intermediate
Test? computation
Level
Main
Function
Body Not in
Final intermediate
computation level
Function call
itself

Restore formal
parameters, local
variable, return address.
Last
Section

End

Control transferred to the return address

➢ Tower Of Hanoi:-

 The tower of Hanoi problem is very popular example in recursion and in stack data structure .The
basic problem is that you have three pole source, aux and destination and in the source pole there
are N different sized disk. Now you have to move these disks from source to destination using aux
pole (The object is to move all the disks over to another pole) but the Rules are:
1) Only one disk may be moved at a time
2) Each move consists of taking the upper disk from one of the pole and sliding it onto another
pole, on top of the other disks that may already be present on that pole.
3) you cannot place a larger disk onto a smaller disk

BMU- BMCCA Page 11 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

 problem solving Process(recursive) is


1) move n-1 disks from source to aux as dest intermediate
2) move the bottom disk from source to dest
3) move n-1 disks from aux to dest using source intermediate
 Algorithm Implementation
Suppose we have a function hanoi(N,src,aux,dest)

hanoi(int x, char from,char to,char aux)


if N = = 1
printf("Move Disk From %c to %c\n",from,to);
else
hanoi(N-1, Src, Dst, Aux)
Move from Src to Dst
hanoi(N-1, Aux, Src, Dst)

 The no of moves required is ((2^n)-1) where n is no of disks at source pole


Code Implementation

#include<stdio.h>
#include<conio.h>
#include<math.h>
void hanoi(int x, char from,char to,char aux)
{
if(x==1)
{
printf("Move Disk [%d] From= [%c] to= [%c] ==> [%c]\n",x,from,to,aux);
}
else
{
hanoi(x-1,from,aux,to);
printf("Move Disk [%d] From= [%c] to= [%c] ==> [%c]\n",x,from,to,aux);
hanoi(x-1,aux,to,from);
}
}
void main()
{
int disk;
int moves;
clrscr();
printf("Enter the number of disks you want to play with:");
scanf("%d",&disk);
moves=pow(2,disk)-1;
printf("\nThe No of moves required is=%d \n",moves);
hanoi(disk,'L','C','R');
getch();
}
BMU- BMCCA Page 12 of 14
Data Structures UNIT : STACK By : Sneha T. Patel

UNIT:- Data structure / Stack


 Short Question Answer (Marks-1 or 2)

1) Give the difference between primitive and non-primitive data structure.


2) List out the non-primitive data structure.
3) List out the computer application of stack.
4) What condition is not necessary in dynamic stack?
5) Define Data Structure. What is advantage of data structure?
6) Convert the following to infix expression:
ABCD+/-
7) Convert to polish notations
a) a * (b – c) + ((a / c) – d)
b) x + ( y / (z – x) / (y + z) * x)
8) Convert to reverse polish notations
a) a * (b + c) + (c + d / (a – b))
b) x + ( y * z) + (p – (q * r) / z)
9) Write prefix and postfix expression for:
(a * b)2 – (c/d-e)
10) Give three examples of real world representation of stack.
11) Convert to the following infix expression to prefix
a) a * (b + (c – a) / d) – c * d
b) p + q * r + (s – p) / (p – (r * s) +q)
12) Explain any two applications of stack with example.
13) Translate the expression into infix notation and then evaluate it
5, 3, +, 3, *, 6, 9, 7, -, /,-
14) What do you mean by polish notation and reverse polish notation? Give one example.
15) What is the use of pop ( ) in stack?
16) Name various primitive and non primitive data structure.
17) Find the address of 4th element of an integer array A[10], if base address is 1050.
18) What is reverse polish notation? Convert postfix expression: ab+de-xy/pq^*^/ to infix expression.

 Long Question Answer (Marks: 5-7)

1) Memory Representation of Array(m-5)


2) Define Stack. Write algorithm to perform various operation on stack.(m-6)

BMU- BMCCA Page 13 of 14


Data Structures UNIT : STACK By : Sneha T. Patel

3) Algorithm to convert infix expression to prefix expression(m-5)


4) Write a algorithm to convert infix to prefix and infix to postfix.(m-8)
5) Convert to reverse polish notation(m-5)
1) p + (q + r) – (q * s /(p – q))
2) a + (b/c) + (d / a + (e – f) ^ g)
3) a * (b – c / (d + a))
6) Convert following Infix expression to postfix and prefix expression:(m-8)
1) (A + B) * (C * D – E) * F
2) A * (B + D) / E – F * (G + H / K)
3) (A + B /D) ^ (E – F) * G)
7) Recursion (m-7or 5)
8) Tower of Hanoi(m-5)
9) What is recursion? Explain its applications, advantages and disadvantages.
10) Write an algorithm to reverse string using stack.(m-7)
11) What is recursive? Explain algorithm to display factorial for given number using algorithm.
12) Explain advantages of recursion. Write a program to find factorial of given no using recursion. (m-
7)
13) Explain Recursion with proper example. State its Pros and Cons. Write a Recursive Function to
find Factorial of given number.(m-8)
14) Evaluate the following postfix expression:
a) 12,7,3,-,/,2,1,5,+,*,+
b) 2,3,10,+,*,8,2,/,-
15) Convert following postfix to infix expression:
a) ab + cd +*
b) abcde ^ * / -
c) ab + c -
d) ab + c * de- -fg+ ^
16) Convert following prefix to infix expression:
a) * + abc
b) + - * ^ abcd/ / ef + gh
c) + a ^ / + * - bc – defg – hj
d) – a / b * c ^ de

BMU- BMCCA Page 14 of 14

You might also like