Module 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 135

STACKS

MODULE 2

Availaible at VTU HUB (Android App)


INTRODUCTION
 The linear lists and linear arrays allows one to insert and
delete elements at any place in the list- at the beginning, at
the end or in the middle
 There are certain frequent situations when one wants to
restricts insertions and deletions so that they can take place
only at the beginning or the end of the list, not in the middle
 They are STACKS and QUEUES

Availaible at VTU HUB (Android App)


STACKS
 “A stack is an ordered linear list in which insertions and deletions
are made at one end called the top.”
 Given a stack S= (a 0, ... ,a n-1), where a 0 is the bottom element,
a n-1 is the top element, and a i is on top of element a i -1, 0 < i < n
 Inserting element to stack is called as PUSH operation.
 Deleting an element from stack is called as POP operation
 PUSH and POP are the primitive operations

 Inserting and deleting elements in a stack

 Inserting and deleting elements


Availaible in a(Android
at VTU HUB stack App)
 If the elements are added in the stack in the order A, B, C, D, E,
then E is the first element that can be deleted from the
stack .
 Since the last element inserted into a stack is the first element
removed, a stack is also known as a Last-In-First-Out (LIFO)
list.
 Hence elements are removed in the order E,D,C,B,A
 Stack is also called as Push down list because new elements are
added on the top of list, there by we are pushing down list
 Size of the stack grows as the items are added and shrinks as the
items are removed. Hence stack is dynamic in nature

Availaible at VTU HUB (Android App)


Stack Operations
 To implement stack concept the two primitive operations
are used
1. PUSH – Used to insert an element into Stack.
2. POP – Used to delete an element from Stack.
 Stack top – used to copy the item at the top of Stack but
does not delete it.
 Underflow and Overflow
Underflow is a condition occurs if we try to POP item
from the empty STACK
Overflow is a condition occurs if we try to PUSH an
ITEM to the STACK which is already full

Availaible at VTU HUB (Android App)


STACK
E D C B A FULL
STACK OVERFLOW

<--TOP
Availaible at VTU HUB (Android App)
POP

D <--TOP

STACK
EMPTY STACK UNDERFLOW
Availaible at VTU HUB (Android App)
Push Algorithm
PUSH(STACK, TOP, MAXSTK, ITEM)
This procedure pushes an ITEM onto a stack
1.[ Stack already filled? ]
If TOP = MAXSTK, then: print: OVERFLOW, and return
2. Set TOP := TOP + 1 [ Increases TOP BY 1]
3. Set STACK[ TOP ] := ITEM [ Inserts ITEM in new TOP
position ]
4. Return

Availaible at VTU HUB (Android App)


POP Algorithm
POP(STACK, TOP, ITEM)
This procedure deletes the top element of STACK and assigns it
to the variable ITEM
1. [ Stack has an item to be removed? ]
If TOP = 0, then: Print : UNDERFLOW, and Return
2. Set ITEM := STACK[ TOP ]. [ Assigns TOP element to ITEM ]
3. Set TOP := TOP – 1. [ Decreases TOP by 1 ]
4. Return

Availaible at VTU HUB (Android App)


Stack representation using arrays in C
#define MAXSTK 8
typedef struct {
char items[MAXSTK];
int top;
}STACK;
STACK s;
s.top = -1;
 Stack can represented using linear array as shown below

Availaible at VTU HUB (Android App)


Push function
 void PUSH(int item)
{
if(s.top==MAX-1) /* stack is full*/
{
printf("\nSTACK is FULL CAN't ADD ITEM\n");
return;
}
s.top++;
s.items[s.top]=item;
}

Availaible at VTU HUB (Android App)


POP function
 int pop( )
{
int item;
if(s.top==-1) /* stack is empty*/
{
printf(“stack empty”);
getch();
exit(0);
}
item=s.item[s.top];
s.top--;
return (item);
}
Availaible at VTU HUB (Android App)
Stacks using dynamic arrays

•The array is used to implement stack, but the bound (MAX_STACK_SIZE)


should be known during compile time.
•The size of bound is impossible to alter during compilation .
•This can be overcome by using dynamically allocated array for the elements
and then increasing the size of array as needed.
int * stack;
int top= -1;
capacity = 1;
stack = (int *) malloc (sizeof (*stack));

int IsFull( ) {
if ( top >= capacity – 1)
return 1;
return 0;
} Availaible at VTU HUB (Android App)
Void Push(int item)
{
If(IsFull( ))
Stackfull( );
Top++;
* stack=item;
return;
}
Stackfull( )
{
Stack=realloc(2*capacity*size of (*stack));
Capacity*=2;
}

Availaible at VTU HUB (Android App)


int Isempty( ){
If(top <0)
return 1;
return 0;
}
int Pop( )
{
int x;
If(!Is empty(s)
{
X=*stack;
Stack--;
return x;
}
}

Availaible at VTU HUB (Android App)


Array doubling
 The new code shown below, attempts to increase the
capacity of the array stack so that new element can
be added into the stack. Before increasing the
capacity of an array, decide what the new capacity
should be.
 In array doubling, array capacity is doubled whenever it
becomes necessary to increase the capacity of an array.
void stackFull()
{
realloc(s , 2*capacity*sizeof(*s));
capacity * = 2;
}
Availaible at VTU HUB (Android App)
Stack Applications
 Postponing data usage
 Reversing Data
 Parsing Data
 Backtracking Steps.

Availaible at VTU HUB (Android App)


Postponing data usage

 A stack can be used in applications that requires that the use


of data be postponed for a while.
 Examples:
1. Infix to postfix transformation
2. Evaluation of postfix expression

Availaible at VTU HUB (Android App)


Evaluation of expression
 Three levels of precedence for the 5 binary operations
 Highest : Exponentiation ( ) or ($) or (^) or (**)
 Next Highest : Multiplication (*) and Division(/)
 Lowest: Addition (+) and Subtraction (-)

Availaible at VTU HUB (Android App)


 2 3 + 5 * 2 2 - 12 / 6
 To evaluate expression is traversed three times, each time
corresponding to the level of precedence of the operations
 After first traversal expression reduces to 8 + 5 * 4 -12 / 6
 After Second traversal expression reduces to 8 + 20 – 2
 After Third traversal expression reduces to 26

Availaible at VTU HUB (Android App)


Arithmetic Expression Representation
 INFIX
 PREFIX – POLISH
 POSTFIX – REVERSE POLISH or SUFFIX
INFIX POLISH REVERSE POLISH

A+B*C +A*BC ABC*+

(A+B)*C *+ABC AB+C*


 Note
 The order of operators and operands in an INFIX expression does not uniquely determine the
order in which operations to be performed
 In POLISH and REVERSE POLISH notation the order in which the operations to be
preformed is completely determined by the position of the operators and the operands in the
expression
 No parenthesis required to determine the order
 Computer evaluates arithmetic expressions in INFIX notation in two steps
 1) Convert INFIX expression to POSTIX
 2) Evaluate the POSTFIX expression
Availaible at VTU HUB (Android App)
 Infix---------postfix
 A+B*C ----A+[BC*]= ABC*+ Postfix
 -----A+[*BC] =+A*BC PREFIX

 A*B+C------[AB*]+C= AB*C+
 ------ [*AB]+C = +*ABC

Availaible at VTU HUB (Android App)


Converting infix to postfix and Prefix -Examples
INFIX
1. A+B*C : A+[BC*] ABC*+ is POSTFIX
A+[*BC] +A*BC is PREFIX
2 (A+B)*C : [AB+]*C AB+C* is POSTFIX
: [+AB]*C *+ABC is PREFIX
3 A$B*C-D+E/F/G+H: [AB$]*C-D+E/F/G+H
(Converting to postfix ) [AB$C*]-D+[EF/G/]+H
AB$C*D-EF/G/+H+ is POSTFIX
(Converting to prefix) [$AB]*C-D+E/F/G+H
[*$ABC]-D+[//EFG]+H
++-*$ABCD//EFGH is PREFIX
Availaible at VTU HUB (Android App)
Converting infix to postfix and Prefix -Examples
INFIX to POSTFIX Conversion
Given Infix Expression: ((A+B)*C-(D-E))$(F+G)
([AB+]*C-[DE-])$[FG+]
([AB+C*]-[DE-])$[FG+]
[AB+C*DE--]$[FG+]
AB+C*DE--FG+$ is Post expression
INFIX to PREFIX Conversion
Given Infix Expression: ((A+B)*C-(D-E))$(F+G)
([+AB]*C-[-DE])$[+FG]
([*+ABC]-[DE-])$[+FG]
[-*+ABC-DE]$[+FG]
$-*+ABC-DE+FG is Prefix expression
Availaible at VTU HUB (Android App)
Evaluation of postfix expression
To evaluate postfix expression, create an empty stack
 Scan from left to right to get a token
 If token is operand place on the stack
 If token is an operator remove two operands from the stack
 Perform the operation on that operands corresponding to the
operator
 Result is placed back on the stack
 Continue the procedure until we reach end of the expression
 Remove the answer from the stack.

Availaible at VTU HUB (Android App)


Algorithm to evaluate POSTFIX expression
 EVALUATE (P)
This algorithm finds the VALUE of an arithmetic expression P written in postfix
notation
1. Append a right parenthesis “)” at the end of P.[this acts as a sentinel]
2. While not end of expression(p)
3. If an operand is encountered, place it on to STACK
4. If an operator is encountered, then,
(a) Remove the two top elements of STACK, where A is the top element and B is the next-
to-top element
(b) Evaluate B operator A
(c) Place the result of (b) back on stack
[End of If structure]
[End of Step 2 loop]
5. Set VALUE equal to the top element on STACK
6. Exit

Availaible at VTU HUB (Android App)


Evaluating Given Postfix Expression :
Example: 6 2/ 3– 42*+
Token Stack top
[0] [1] [2]
Initially -1
6 6 0
2 6 2 1
/ 3 0
3 3 3 1
- 0 0
4 0 4 1
2 0 4 2 2
* 0 8 1
+ 8 0
eos Availaible at VTU HUB (Android App) -1 Answer=8
Postfix Evaluation
Postfix expression
62/3–42*+

Availaible at VTU HUB (Android App)


stack

Postfix Expression
2/3–42*+

Token
Operand,
6 PUSH onto
stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression
2/3–42*+

Availaible at VTU HUB (Android App)


stack

Postfix Expression
/3–42*+

Token
Operand,
2 PUSH onto
stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression
/3–42*+

2
6

Availaible at VTU HUB (Android App)


stack

Postfix Expression
3–42*+

Token
Operator, POP
/ 2 top elements
from the stack
2
and store it in
6 opnd2 and
opnd1
Availaible at VTU HUB (Android App)
stack

Postfix Expression
3–42*+

opnd1 opnd2
6 2

Availaible at VTU HUB (Android App)


stack

Postfix Expression
3–42*+
Evaluate
opnd1 opnd2
opnd1
6 2 operator
opnd2

Availaible at VTU HUB (Android App)


stack

Postfix Expression
3–42*+

opnd1 opnd2 Res


6 / 2 3

PUSH Res onto stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression
3–42*+

Availaible at VTU HUB (Android App)


stack

Postfix Expression
–42*+

Token
Operand,
3 PUSH onto
stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression
–42*+

3
3

Availaible at VTU HUB (Android App)


stack

Postfix Expression
42*+

Token
Operator, POP
- 2 top elements
from the stack
3
and store it in
3 opnd2 and
opnd1
Availaible at VTU HUB (Android App)
stack

Postfix Expression
42*+
Evaluate
opnd1 opnd2
opnd1
3 3 operator
opnd2

Availaible at VTU HUB (Android App)


stack

Postfix Expression
42*+

opnd1 opnd2 Res


3 - 3 0

PUSH Res onto stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression
42*+

Availaible at VTU HUB (Android App)


stack

Postfix Expression
2*+

Token
Operand,
4 PUSH onto
stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression
2*+

4
0

Availaible at VTU HUB (Android App)


stack

Postfix Expression
*+

Token
Operand,
2 PUSH onto
stack
4
0

Availaible at VTU HUB (Android App)


stack

Postfix Expression
*+

2
4
0

Availaible at VTU HUB (Android App)


stack

Postfix Expression
+

Token
Operator, POP
2 * 2 top elements
from the stack
4
and store it in
0 opnd2 and
opnd1
Availaible at VTU HUB (Android App)
stack

Postfix Expression
+
Evaluate
opnd1 opnd2
opnd1
4 2 operator
opnd2

Availaible at VTU HUB (Android App)


stack

Postfix Expression
+

opnd1 opnd2 Res


4 * 2 8

PUSH Res onto stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression
+

8
0

Availaible at VTU HUB (Android App)


stack

Postfix Expression

Token
Operator, POP
+ 2 top elements
from the stack
8
and store it in
0 opnd2 and
opnd1
Availaible at VTU HUB (Android App)
stack

Postfix Expression

Evaluate
opnd1 opnd2
opnd1
0 8 operator
opnd2

Availaible at VTU HUB (Android App)


stack

Postfix Expression

opnd1 opnd2 Res


0 + 8 8

PUSH Res onto stack

Availaible at VTU HUB (Android App)


stack

Postfix Expression

Availaible at VTU HUB (Android App)


Infix to Postfix -Conversion process
 Since the order of operands in the infix and postfix expression is same ,Scan the
input infix expression from left to right
 During the scan ,operands are passed directly to the postfix expression as they
are encountered.
 When the operators are encountered it is placed in the postfix expression
depending on its precedence
 To get the higher precedence first in the postfix expression, we save the
operators until we know their correct placement. To do this we follow the
following procedure
 Check the precedence of the incoming operator with the stack top.
if precedence of incoming operator is not higher than the operator at the stack top
repeatedly pop the stack and place the popped item to the postfix expression.
 place incoming operator on the stack.
 Once you reach end of infix expression repeatedly pop the stack and place the
popped item to the postfix expression till stack is empty

Availaible at VTU HUB (Android App)


 In a parenthesized infix expression the expression inside
the parenthesis should be converted first.
 Hence we stack the operators until we reach the right
parenthesis
 As we encounter left parenthesis during scanning, we
must place it on the stack what ever may be the stack
top. Once left parenthesis becomes the stack top, what
ever may be the operators other than the right
parenthesis ,the operator should be placed on the stack
 Hence left parenthesis need to behave like high
precedence when it is out from the stack and low
precedence operator when it is on the stack.

Availaible at VTU HUB (Android App)


Infix to postfix conversion algorithm
 Conversion(Infix, Postfix) //Algorithm converts INFIX expression into POSTFIX expression
1 push “#“ onto STACK
2 scan Infix expression from left to right and repeat Steps 3 to 6 for each element until end
of Infix expression
3 If an operand is encountered place it in the POSTFIX expression
4 If an left parenthesis is encountered, push it on to the STACK
5 If a right parentheses is encountered
a) Repeatedly pop from the STACK and place it in the Postfix until left parenthesis is
encountered
b) Remove the left parenthesis
[ End of If ]
6 If an operator is encountered, call it as incoming operator, then:
a) If precedence of incoming operator is less than precedence of stack top then :
Repeatedly pop from the STACK and place it in the Postfix
b) Place the incoming operator to the STACK
[End of IF]
[ End of Step 2 loop ]
Availaible at VTU HUB (Android App)
7. If stack top !=„#‟
Repeatedly pop from the STACK and place it in the Postfix until „#‟ is
encountered

Availaible at VTU HUB (Android App)


Infix to postfix conversion
infixVect
(a+b-c)*d–(e+f)

postfixVect

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
a+b-c)*d–(e+f)

postfixVect

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
+b-c)*d–(e+f)

postfixVect
a

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
b-c)*d–(e+f)

postfixVect
a

+
(

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
-c)*d–(e+f)

postfixVect
ab

+
(

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
c)*d–(e+f)

postfixVect
ab+

-
(

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
)*d–(e+f)

postfixVect
ab+c

-
(

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
*d–(e+f)

postfixVect
ab+c-

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
d–(e+f)

postfixVect
ab+c-

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
–(e+f)

postfixVect
ab+c-d

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
(e+f)

postfixVect
ab+c–d*

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
e+f)

postfixVect
ab+c–d*

(
-

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
+f)

postfixVect
ab+c–d*e

(
-

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
f)

postfixVect

+ ab+c–d*e

(
-

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect
)

postfixVect

+ ab+c–d*ef

(
-

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+

Availaible at VTU HUB (Android App)


Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+-

Availaible at VTU HUB (Android App)


Infix to Postfix Conversion using Stack: Example

Infix Expression : A *(B + C) / D


Token Stack top Postfix
[0] [1] [2]
A -1 A
* * 0 A
( * ( 1 A
B * ( 1 AB
+ * ( + 2 AB
C * ( + 2 A BC
) * 0 ABC+
/ / 0 ABC+*
D / 0 ABC+*D
eos -1 ABC+*D/

Availaible at VTU HUB (Android App)


STACKS & QUEUES

MODULE 2
PART-2

Availaible at VTU HUB (Android App)


Stacks using dynamic arrays

•The array is used to implement stack, but the bound (MAX_STACK_SIZE)


should be known during compile time.
•The size of bound is impossible to alter during compilation .
•This can be overcome by using dynamically allocated array for the elements
and then increasing the size of array as needed.
int * stack;
int top= -1;
capacity = 1;
stack = (int *) malloc (sizeof (*stack));

int IsFull( ) {
if ( top >= capacity – 1)
return 1;
return 0;
} Availaible at VTU HUB (Android App)
Void Push(int item)
{
If(IsFull( ))
Stackfull( );
Top++;
Stack[Top]=item;
return;
}
Stackfull( )
{
Stack=realloc(2*capacity*size of (*stack));
Capacity*=2;
}

Availaible at VTU HUB (Android App)


int Isempty( ){
If(top <0)
return 1;
return 0;
}
int Pop( )
{
int x;
If(!Is empty(s)
{
X=stack[Top];
Top--;
return x;
}
}

Availaible at VTU HUB (Android App)


Array doubling
 The new code shown below, attempts to increase the
capacity of the array stack so that new element can
be added into the stack. Before increasing the
capacity of an array, decide what the new capacity
should be.
 In array doubling, array capacity is doubled whenever it
becomes necessary to increase the capacity of an array.
void stackFull()
{
realloc(s , 2*capacity*sizeof(*s));
capacity * = 2;
}
Availaible at VTU HUB (Android App)
Reversing Data

 Reversing a list
 Reversing Data: We can use stacks to reverse data.
(example: files, strings) rsum=0 num=25652 while
num!=0
Very useful for finding palindromes. Reminder=num%10= 2
num=num/10=0
Pseudocode: Stack=2,5,6,5,2
while(!empty()) x=pop()
1) read (data) rsum =rsum*10+x
2) loop (data not EOF and stack not full) =25652
1) push (data)
2) read (data)
3) Loop (while stack notEmpty)
1) pop (data)
2) print (data)

Availaible at VTU HUB (Android App)


 Converting Decimal to Binary: Consider the following pseudo code
1) Read (number)
2) Loop (number > 0)
1) digit = number modulo 2
2) print (digit)
3) number = number / 2
// from Data Structures by Gilbert and Forouzan

The problem with this code is that it will print the binary
number backwards. (ex: 19 becomes 11001000 instead of 00010011. )
To remedy this problem, instead of printing the digit right away, we can
push it onto the stack. Then after the number is done being converted, we
pop the digit out of the stack and print it.

Availaible at VTU HUB (Android App)


Parsing Data

 Parsing is any logic that breaks data into independent pieces


for further processing. One common problem is unmatched
parenthesis in an algebraic expression. This error can checked
by using stack

Availaible at VTU HUB (Android App)


Backtracking Steps.

 Goal seeking
 Decision Analysis

Availaible at VTU HUB (Android App)


Recursion
 Recursion is a process in which a procedure calls itself. In C
the function that calls itself is called as recursive function.
 Two types
1. Direct recursion – if the function A calls function A itself
2. Indirect recursion – if function A calls function B, function
B calls function A ( recursive chain)
 A recursive procedure must have the following 2 properties
1. There must be base criteria ( terminating condition) for
which procedure doesn’t calls itself
2. Successive recursive calls should lead towards base criteria

Availaible at VTU HUB (Android App)


Recursion - Examples
 Recursion is implemented by means of Stacks.
 Factorial function – f(n) = n*f(n-1) for n != 0
f(n) = 1 for n = 0
Algorithm:
FACTOIAL (FACT, N)
This procedure calculates N! and returns the value in the variable FACT
1) If N = 0, then Set FACT := 1 and Return
2) Call FACTORIAL (FACT, N-1)
3) Set FACT := N * FACT
4) Return

Availaible at VTU HUB (Android App)


 Factorial(Fact,5)
Factorial(Fact,4)
Factorial(Fact,3)
Factorial(Fact,2)
Factorial(Fact,1)
Factorial(Fact,0)
Fact=1*1
Fact=2*1
Fact=3*2
Fact=4*6
Fact=5*24 =120
Availaible at VTU HUB (Android App)
Fibonacci number
 Fibonacci sequence- fib(n) = fib(n-1) + fib (n-2) for n > 1
fib(n) = n for n=0 or n=1
Algorithm:
FIBONACCI (FIB, N)
This procedure calculates FN and returns the value in the first
parameter FIB
1) In N = 0 or N=1 then: Set FIB := N, and Return.
2) Call FIBONACCI (FIBA, N-2)
3) Call FIBONACCI (FIBB, N-1)
4) Set FIB := FIBA + FIBB
5) Return

Availaible at VTU HUB (Android App)


GCD
 GCD – gcd(m, n) = gcd( n, m mod n) for n != 0
gcd (m,n) = m for n = 0
Algorithm:
GCD(m, n)
This procedure calculates the GCD of two numbers m, n and Returns
the value
1. If n=0 then, Set gcd := m; Return gcd
2. Call GCD ( n, m mod n)
3. End

Availaible at VTU HUB (Android App)


Tower of Hanoi
 In this puzzle, we have 3 towers or pegs and n disks of different
sizes .
 Initially, all the disks are on the first peg called source peg in
proper order of size, that is the largest on the bottom and
the smallest on top.
 The goal is to move all the disks to the third peg called
destination peg using the second one as an auxiliary, if
necessary.
 We can move only one disk at a time, and it is forbidden to
place a larger disk on top of a smaller one.

Availaible at VTU HUB (Android App)


Tower of Hanoi :
In this puzzle, we have 3 towers or pegs and n disks of different sizes .

Initially, all the disks are on the first peg called source peg in proper order of
size, that is the largest on the bottom and the smallest on top.

The goal is to move all the disks to the third peg called destination peg using the
second one as an auxiliary, if necessary.

We can move only one disk at a time, and it is forbidden to place a larger disk on
top of a smaller one.

Availaible at VTU HUB (Android App)


Availaible at VTU HUB (Android App)
Solution to Tower of Hanoi Problem
 move top n-1 disks from source peg A to peg B using peg C as Auxpeg
 Transfer the remaining disk from peg A to peg C
 move n-1 disks from peg B to peg C using peg A as Auxpeg
Algorithm:
TOWER (N, Src, Aux, Dest)
//This procedure gives a recursive solution to the Towers of Hanoi problem for N disks
1) If N=1 then :
Write : move disk 1 from Src to Dest and Return
[ End of If structure ]
2) [ Move N-1 disks from peg Src to peg Aux ]
Call TOWER( N-1, Src, Dest, Aux)
3) Write : move disk N from Src to Dest
4) [ Move N-1 disks from peg Aux to peg Dest ]
Call TOWER( N-1, Aux,Src, Dest)
5) Return

Availaible at VTU HUB (Android App)


Recursive solution - Traces for n=3
Tower(3,A,B,C)
Tower(2,A,C,B)
Tower(1,A,B,C)
Move disk 1 from A to C
Move disk 2 from A to B
Tower(1,C,A,B)
Move disk 1 from C to B
Move disk 3 from A to C
Tower(2,B,A,C)
Tower(1,B,C,A)
Move disk 1 from B to A
Move disk 2 from B to C
Tower(1,A,B,C)
Move disk 1 from A to C
Availaible at VTU HUB (Android App)
Ackermann function

 It is a function with 2 arguments which can be


assigned non negative integer ( 0, 1,2…..).
 Ackermann function is defined as follows.
A(m, n)= n+1 if m = 0
A(m, n) = A(m-1, 1) if m != 0 and n = 0
A(m, n) = A(m-1, A(m, n-1)) if m != 0 and n != 0

Availaible at VTU HUB (Android App)


Example
A(1,3) = A(0, A(1,2))
A(1,2) = A(0,A(1,1))
A(1,1) = A(0,A(1,0))
A(1, 0 ) = A(0,1)
A(0,1) = 1+1 = 2
A(1,0) = 2
A (1,1) = A(0,2) = 2+1 = 3
A(1,2) = A(0,3) = 3+1 = 4
A(1,3) = A(0,4) = 4+1 = 5

Availaible at VTU HUB (Android App)


QUEUES
 Queue is a linear list of elements in which insertion and deletion take
place at different ends. The end at which new element is inserted is
called as rear and the end from which element is deleted is called as
front
 Queue has the property - FIFO
 To implement queue front and rear variables are used

A B C D

front rear
Availaible at VTU HUB (Android App)
Data structure for Queue
#define MAXQ 25
typedef struct {
int front, rear;
char item[MAX];
}QUEUE;
QUEUE q;
q.rear = -1;
q.front = -1;

Availaible at VTU HUB (Android App)


Primitive operations – Qinsert, Qdelete
Void Qinsert (char element)
{
If (q.rear ==MAXQ-1) {
Queue full();
Exit(0);
}
q.item[++q.rear]=element;
Return;
}
Char Qdelete( )
{
If (q.front==q.rear)
Return(emptyQ( );
Return (q.item[++q.front]);
Availaible at VTU HUB (Android App)
Example: Job scheduling

 Queues are frequently used in creation of a job queue by an operating


system. If the operating system does not use priorities, then the jobs
are processed in the order they enter the system.
 Figure illustrates how an operating system process jobs using a sequential
representation for its queue.

Availaible at VTU HUB (Android App)


Disadvantage of ordinary queue
Once MAXQ items are added, even if we delete the items from
Front, we can not add items in vacant places. This is because rear
has reached MAXQ value and there is no way to come back to
deleted element position.
This problem may be solved by using array compaction on every item deletion
or by viewing queue as circular not as straight line.
In array compaction method, Qdelete function should be changed as
given below. In this case front is always 0.
Char Qdelete( ){
If(q.rear>=0){
X=q.items[0];
For(i=0; i< q.rear; i++)
q.items[i]=q.items[i+1];
q.rear--;
}} Availaible at VTU HUB (Android App)
CIRCULAR QUEUES
 It is “The queue which wrap around the end of the array.” The array
positions are arranged in a circle as shown in figure.
 In this convention the variable front points one position counter
clockwise from the location of the front element in the queue.
 The rear is points to the item at rear end

Availaible at VTU HUB (Android App)


Circular Queue
When an array is used to have a circular queue : Front is one
position counterclockwise from the first element and rear is current end

[3] [4]
C D
[2] [5]
B E

A F
[6]
[1] G

[0] [7]
Front=0, Rear=7

A B C D E F G

Front=0, Rear=7
Availaible at VTU HUB (Android App)
Implementation of Circular Queue
Operations
 When the array is viewed as a circle, each array position has a next and a
previous position. The position next to MAX-QUEUE-SIZE -1 is 0,
and the position that precedes 0 is MAX-QUEUE-SIZE -1.
 When the queue rear is at MAX_QUEUE_SIZE-1, the next element is
inserted at position 0.
 In circular queue, the variables front and rear are moved from their
current position to the next position in clockwise direction. This
may be done using code
if (rear = = MAX_QUEUE_SIZE-1)
rear = 0;
Else
rear++;
 This can be done by using the modulus operator, which computes
remainders.
(rear +1) % MAX_QUEUE_SIZE
Availaible at VTU HUB (Android App)
[3] [4]

C D
[2] [5]
B E

A F
[6]
[1] G

[0] [7]

Front=0, Rear=7

 When queue is empty, then front =rear.


 When the queue becomes full rear equals front if we use its
full capacity.
 Hence we cannot distinguish between an empty and a full
queue.
To avoid the resulting confusion, we restrict capacity of
Queue one lessAvailaible
than actual capacity.
at VTU HUB (Android App)
Data structure for Circular Queue
#define MAXQ 8
typedef struct {
int front, rear;
char items[MAX];
}CQUEUE;
CQUEUE cq;
cq.rear = 0;
cq.front = 0;

Availaible at VTU HUB (Android App)


Program: Add to a circular queue
void addq(char item)
{ /* add an item to the queue */
cq.rear = (cq.rear +1) % MAX_QUEUE_SIZE;
if (cq.front == cq.rear)
CqueueFull(); /* print error and exit */
cq.items [cq.rear] = item;
}
CqueueFull()
{
If(cq.rear==0)
Cq.rear= MAX_QUEUE_SIZE-1
Else
Cq.rear--; } Availaible at VTU HUB (Android App)
Program: Delete from a circular
queue
 char deleteq()
{ /* remove front element from the queue */
if (cq.front == cq.rear)
return CqueueEmpty( ); /* return an error key */
cq.front = (cq.front+1)% MAX_QUEUE_SIZE;
return cq.items[cq.front];
}

Availaible at VTU HUB (Android App)


CIRCULAR QUEUES USING DYNAMIC ARRAYS
 A dynamically allocated array is used to hold the queue elements.
Let capacity be the number of positions in the array queue.
 To add an element to a full queue, first increase the size of this array
using a function realloc. As with dynamically allocated stacks, array
doubling is used.
 Consider the full queue of figure shown below. This figure shows a
queue with seven elements in an array whose capacity is 8.
There can be two cases. one in which front=0, other one with
front!=0. This can be better understood by flattening out the array.

Availaible at VTU HUB (Android App)


When Front=0

A B C D E F G

Front=0 Rear= 7

Availaible at VTU HUB (Android App)


When Front !=0

Availaible at VTU HUB (Android App)


Algorithm for Circular Queue using Dynamically allocated Array

1. Create a new array newQueue of twice the capacity.


2. If front==0
Copy queue[front+1] through queue[capacity-1] to positions
in newQueue beginning at 0 and go to step 5.
3. Copy the second segment( ie, queue[front+1] through
queue[capacity-1])to positions in newQueue beginning at 0.
4. Copy the first segment (ie, elements queue[0] through
queue[rear] to positions in newQueue beginning at
capacity-front-1.
5. Update rear=capacity -2,front=2*capacity-1,
capacity=2*capacity

Availaible at VTU HUB (Android App)


 Void addcq(char item)
{
rear=(rear+1)% capacity;
If (front==rear) qfull( );
Cq[rear]=item;
}

Availaible at VTU HUB (Android App)


Note: The function Copy(a, b, c) copies elements from locations a
through b-1 to locations beginning at c
Void qfull( ){ // queue is the current circular queue
char *new Queue;
new Queue= (char*)malloc(2*capacity*sizeof(*queue));
int start =(front+1)%capacity;
If(start<2)
Copy(queue+start, queue+start+capacity-1, new Queue);
Else {
Copy(queue+start, queue+capacity, new Queue);
Copy(queue, queuerear+1, new Queue+capacity-start);
}
Front=2*capacity-1;
Rear=capacity-2;
Capacity =2* capacity;
Free(queue);
queue= newQueue;
Availaible at VTU HUB (Android App)
}
Dequeues
 Double ended queue is one in which elements can be
inserted or deleted at either end but not in the middle.
 Deques are implemented as circular queue
 2 types of dequeue are
1.Output restricted – allows deletion at only one end (front)
but insertion at both ends
2.Input restricted - allows insertion at only one end (rear)
but deletion at both ends

Availaible at VTU HUB (Android App)


Dequeues -Implementation
 Initially left=right=Null
 When first element is placed then set both left and right to 1.
 To add an element to the Dequeue check whether it is full,
X=right+1, if X>MAXQ set X=1
if (left == X) CQ is full , We can not insert
 If Deque is not full
To add an element to the left update left and then insert
ie, if left == 1 then set left= N
Else left=left-1
To add an element to right update right and then insert
ie, if right == N then set right= 1
Else right=right+1
.
Availaible at VTU HUB (Android App)
 To delete an element from the Deque
check whether it is empty, ie, if left== 0 Deque is empty
 When dequeue has only one element ie, Left is equal to right
before deletion, then set left=right=0 after deletion.
 To delete from the left, Copy item at the left then update left
if left == N then set left= 1
Else left=left+1
 To delete from the right, Copy item at the right then update
the right
if right == 1 then set right= N
Else right=right-1
Availaible at VTU HUB (Android App)
Priority queues (PQ)
 Priority Queue is a data structure in which the elements are
assigned priority such that the order in which elements are
deleted and processed follow the following rule
 Element with the higher priority is processed before
elements with lower priority
 Elements with same priority are processed in the order they
are added to the queue
 2 types of PQ are
Ascending PQ (APQ): In which items are inserted arbitrarily
and from which smallest item can be removed. The basic
operations are pqinsert(apq,x) and pqmindelete(apq)
Descending PQ (DPQ): In which items are inserted
arbitrarily and from which largest item can be removed. The
basic operationsAvailaible
are pqinsert(dpq,x)
at VTU HUB (Androidand
App) pqmaxdelete(dpq)
Array representation of priority queue using 2D array

FRONT REAR
1 2 3 4 5 6
2 2
1 A
1 3 2 B C X
0 0 3
4 F D E
5 1
5 G
4 4

Availaible at VTU HUB (Android App)


 Algorithm: delete an element in a priority queue
 Step 1: find smallest K such that FRONT[K] is not NULL
 Step2: delete and process the front element in row K of
QUEUE
 Step3: exit
 Algorithm: inserting an element with priority number M
 Step 1: insert ITEM as the rear element in row M of QUEUE
 Step 2:exit

Availaible at VTU HUB (Android App)


Availaible at VTU HUB (Android App)
One way list representation of priority queue

INFO PRN LINK

1 0
AVAIL 5
2 A 2 6

3 K 4 0
START 7
4 T 1 2

5 1

6 B 3 8

7 X 1 4

8 C 4 3

Availaible at VTU HUB (Android App)


 Algorithm: to delete and process the first element in
PQ
 Step 1: Set ITEM:= INFO [ START ]
 Step2: Delete the first node from the list, process the ITEM
 Step 3: Exit
 Algorithm: to insert an ITEM with priority number N
to PQ
 Step 1: Traverse the one way list until we find a node X whose
priority number exceeds N. insert ITEM in front of node X
 Step 2: If no such node is found, insert ITEM as the last element
of list
 Step 3:Exit
Availaible at VTU HUB (Android App)
Insertion

Availaible at VTU HUB (Android App)


Multiple stacks and queues
We can have two stacks in a single array as given below
top 2=MAX
m[0], m[1], …, m[n-2], m[n-1]

bottommost bottommost
stack 1 stack 2

Stack 1 grows from m[0] to m[ MAX-1]


Stack 2 grows from m[ MAX-1] to m[0]
top1 and top2 are the variables corresponding to stack1,
stack2 respectively and Initialized, top1= -1 and
top2=MAX to start with empty stacks.
Correspondingly Push and Pop methods are written.
When top1=top2 condition is met both stacks are full. top 1=-1
Availaible at VTU HUB (Android App)
MULTIPLE STACKS AND QUEUES

 To have multiple stacks, consider an one dimensional array


memory[MEMORY_SIZE].
 To have n stacks , we divide the available memory into n segments.
 Then i refers to the stack number of one of the n stacks.
 To establish this stack, create indices for both the bottom and top
positions of this stack.
 boundary[i] points to the position immediately to the left of the
bottom element of stack i and top[i] points to the top element.
 Stack i is empty iff boundary[i]=top[i].

Availaible at VTU HUB (Android App)


• Let n is the number of stacks = MAX_STACKS, and m = MEMORY_SIZE.
Initially, boundary[0]=top[0]=-1 and top[i] =boundary[i] =(MEMORY_SIZE/n)*i;.
Stack i grow from boundary[i] + 1 to boundary [i + 1] before it is full. A boundary
for the last stack is needed, so set boundary [n] to MEMORY_SIZE-1.

0 1 [ m/n ] 2[ m/n ] m-1

boundary[ 0] boundary[1] boundary[ 2] boundary[n]


top[ 0] top[ 1] top[ 2]

All stacks are empty and divided into roughly equal segments.

Availaible at VTU HUB (Android App)


Availaible at VTU HUB (Android App)
The declarations are:
#define MEMORY_SIZE 100 /* size of memory */
#define MAX_STACKS 10 /* max number of stacks plus 1 */
element memory[MEMORY_SIZE]; /* global memory declaration */
int top [MAX_STACKS];
int boundary [MAX_STACKS] ;
int n; /*number of stacks entered by the user */
top[0] = boundary[0] = -1;
for (i = 1; i < n; i++)
top[i] =boundary[i] =(MEMORY_SIZE/n)*i;
boundary[n] = MEMORY_SIZE-1;

Availaible at VTU HUB (Android App)


void add(int i, element item)
{ /* add an item to the ith stack */
if (top[i] == boundary [i+1])
stack_full(i); //may have unused storage
memory[++top[i]] = item;
}

element delete(int i)
{ /* remove top element from the ith stack */
if (top[i] == boundary[i])
return stack_empty(i);
return memory[top[i]--];
}

55
Availaible at VTU HUB (Android App)
 The top[i] == boundary[i+1] condition in push implies only
that a particular stack ran out of memory, not that the entire
memory is full. But still there may be a lot of unused space
between other stacks in array memory as shown in Figure.
 Therefore, create an error recovery function called stackFull ,
which determines if there is any free space in memory. If there
is space available, it should shift the stacks so that space is
allocated to the full stack.

Availaible at VTU HUB (Android App)


Availaible at VTU HUB (Android App)
Method to design stack Full
 Determine the least, j, i < j < n, such that there is free space between
stacks j and j+1.That is, top[j ] < boundary[j+l]. If there is a j, then move
stacks i+l,i+2, .., j one position to the right (treating memory[O] as
leftmost and memory[MEMORY_SIZE - 1] as rightmost).This creates a
space between stacks i and i+1.
 If there is no j as in (1), then look to the left of stack i. Find the
largest j such that 0 ≤ j ≤ i and there is space between stacks j and j+ 1 ie,
top[j] < boundary[j+l]. If there is a j, then move stacks j+l, j+2, ... , i one
space to the left.This also creates space between stacks i and i+1.
 If there is no j satisfying either condition (1) or condition (2), then
all MEMORY_SIZE spaces of memory are utilized and there is no free space.
In this case stackFull terminates with an error message.

Availaible at VTU HUB (Android App)

You might also like