You are on page 1of 92

Linked list Questions

•Write a procedure ADD (COEF, EXP, LINK,


POLY1,POLY2,AVAIL,SUMPOLY) which finds the sum
SUMPOLY of POLY1 and POLY2with one variable.
•Write a procedure which finds number of times a given
ITEM occurs in LIST.
•Suppose POLY1 and POLY2 are polynomials (in one
variable) which are stored as header circular lists using the
same parallel arrays COEF, EXP and LINK. Write a procedure
ADD (COEF, EXP, LINK, POLY1, POLY2, AVAIL, and SUMPOLY)
which finds the sum SUMPOLY of POLY1 and POLY2
•Write an algorithm which creates a copy of the singly
linked list LIST stored in a memory
•How to sort the given linked list
•Write an algorithm which deletes last node from LIST
(S.L.L.)
• Reverse given word
• Undo Utility
Stacks
• Stack: what is it?
• ADT
• Applications
• Implementation(s)
Stack: what is it?
• STACK:- is a linear structure in which
items may be added or removed only at
one end
• A stack is a sequence of items that are
accessible at only one end of the
sequence
What is a stack?
• Stores a set of elements in a particular order
• Stack principle: LAST IN FIRST OUT
• = LIFO
• It means: the last element inserted is the first
one to be removed
• Example
• Which is the first element to pick up?
Insertion on Stack
Deletion from Stack
Last In First Out

top
top E
D D D
C top C C C
B top B B B B
A A A A A
A top
Stack Applications
• Real life
– Pile of books
– Plate trays
• More applications related to computer science
• Parsing
• Recursive Function
• Calling Function
• Expression Evaluation
• Expression Conversion
– Infix to Postfix
– Infix to Prefix
– Postfix to Infix
– Prefix to Infix
• Towers of hanoi
Applications of Stacks
• Direct applications
– Page-visited history in a Web browser
– Undo sequence in a text editor
– Saving local variables when one function calls
another, and this one calls another, and so on.
• Indirect applications
– Auxiliary data structure for algorithms
– Component of other data structures
Array-based Stack Implementation
• Allocate an array of some size (pre-defined)
– Maximum N elements in stack
• Bottom stack element stored at element 0
• last index in the array is the top
• Increment top when one element is pushed,
decrement after pop
How to insert an ITEM
PUSH(STACK,TOP,MAXSTK,ITEM)
• This procedure pushes an ITEM onto a
sack
1.[Stack already filled ?]
If TOP=MAXSTK,then:
print:OVERFLOW, and Return.
2.Set TOP:=TOP+1[increase TOP by 1]
3.Set STACK[TOP]:=ITEM
[insert ITEM in new TOP position]
4.Return
How to remove an ITEM?
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,Return.
2. Set ITEM:=STACK[TOP].
[Assigns TOP elements to ITEM .]
3. Set TOP:=TOP-1.[Decreases TOP by 1]
4. Return.
Linked representation of Stack
PUSH_LINKSTACK(INFO,LINK,TOP, AVAIL,ITEM)
This procedure pushes an ITEM into a linked STACK.
1.[Available space?]
If AVAIL=NULL,then, Write VERFLOW and Exit.
2. [Remove 1st node from AVAIL list]
Set NEW:=AVAIL and AVAIL:=LINK[AVAIL]
3. Set INFO[NEW]:=ITEM[copy ITEM in new node]
4. Set LINK[NEW]:=TOP[new node points to original top
node in stack]
5. Set TOP=NEW
[Reset TOP to point to new node at the stack]
6. Exit
POP_LINKSTACK(INFO,LINK,TOP,AVAIL,ITEM)
This procedure deletes the top element of linked stack and
assigns it to variable ITEM.
1. [Stack has an item to be removed?]
If TOP=NULL then Write:UNDERFLOW and Exit.
2. Set ITEM :=INFO[TOP][copy TOP element of stack
into ITEM]
3. Set TEMP:=TOP and TOP:=LINK[TOP]
[Remember the old value of TOP pointer in TEMP and
reset TOP value to point to next element in stack ]
4. [Return deleted node to the AVAIL list]
Set LINK[TEMP]=AVAIL and AVAIL=TEMP.
5. Exit.
Simple Applications of the ADT Stack:
Checking for Balanced Braces
• A stack can be used to verify whether a program contains
balanced braces
– An example of balanced braces

abc{defg{ijk}{l{mn}}op}qr
– An example of unbalanced braces

abc{def}}{ghij{kl}m
abc{def}{ghij{kl}m
Checking for Balanced Braces
• Requirements for balanced braces
–Each time you encounter a “}”, it
matches an already encountered
“{”
–When you reach the end of the
string, you have matched each “{”
Checking for Balanced Braces

Figure Traces of the algorithm that checks for balanced braces


Evaluating Postfix Expressions
• A postfix (reverse Polish logic) calculator
– Requires you to enter postfix expressions
• Example: 2 3 4 + *
– When an operand is entered, the calculator
• Pushes it onto a stack
– When an operator is entered, the calculator
• Applies it to the top two operands of the
stack
• Pops the operands from the stack
• Pushes the result of the operation on the
stack
Evaluating Postfix Expressions

Figure -The action of a postfix calculator when evaluating the expression 2 * (3 + 4)


Evaluating Postfix Expressions
1. Add a right parenthesis “)” at the end of P.[this act
as a sentinel]
2. Scan P from left to right and repeat steps 3 & 4 for
each element of P until sentinel “)” is encountered
3. If an operand is encountered ,put it on STACK.
4. If an operator is encountered, then:
a) Remove the two top elements of STACK, where A is
the top element & B is 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
GATE questions
• The result evaluating the postfix expression 10
5 + 60 6 / * 8 – is
(A) 284
(B) 213
(C) 142
(D) 71

Answer: (C)
2) In evaluating the arithmetic expression 2 * 3-
(4+5), using stacks to evaluate its equivalent
post-fix form, which of the following stack
configuration is not possible?
A)4,6 b)5,4,6 C) 9,9 D)9,3,2
3) Stack A has the entries a, b, c (with a on top),
Stack B is empty. An entry popped out of stack A
can be printed immediately or pushed to stack
B. An entry popped out of stack B can only be
printed. In the arrangement, which of the
following permutations of a, b, c is not possible?
A)b,a,c B)b,c,a C)c,a,b D)a,b,c
• The evaluated value of POSTFIX EXPRESSION 4
3 * 4 2 / - 3 2 $ 2 * + is ………………

• How many stack will be needed for the


evaluation of a prefix expression
a. 1 b.2 c. 0 d. 3
Converting between notations
• INFIX to PREFIX : (A+B) – (C*D)
– Do the first brace: (A+B), the PREFIX is +AB
– Do the second brace: (C*D), the PREFIX is *CD
– The end is operator -: +AB - *CD, the PREFIX is -
+AB*CD
• INFIX to POSTFIX : (A+B) – (C*D)
– Do the first brace: (A+B), the POSTFIX is AB+
– Do the second brace: (C*D), the POSTFIX is CD*
– The end is operator -: AB+ - CD*, the POSTFIX is AB+CD*-
• PREFIX to INFIX : +/*A B C D
– Find the first operator: *, take 2 operands before the
operator (A and B), the INFIX is (A*B)
– Find the second operator: /, take 2 operands before the
operator (A*B and C), the INFIX is ((A*B)/C)
– Find the third operator: +, take 2 operands before the
operator (((A*B)/C) and D), the INFIX is ((A*B)/C)+D
Converting between notations cont..
• PREFIX to POSTFIX : +/*A B C D
Find the first operator: *, take 2 operands before the operator (A and B), the
POSTFIX is AB*
Find the second operator: /, take 2 operands before the operator(AB* and C),
the POSTFIX is AB*C/
Find the third operator: +, take 2 operands before the operator
(AB*C/ and D), the POSTFIX is AB*C/D+
• POSTFIX to INFIX : ABCD*/-
Find the first operator: *, take 2 operands before the operator
(C and D), the INFIX is (C*D)
Find the second operator: /, take 2 operands before the operator
((C*D) and B), the INFIX is (B/(C*D)
Find the third operator: -, take 2 operands before the operator
((B/(C*D) and A), the INFIX is A – (B/(C*D)
• POSTFIX to PREFIX : ABCD*/-
Find the first operator: *, take 2 operands before the operator
(C and D), the PREFIX is *CD
Find the second operator: /, take 2 operands before the operator
(*CD and B), the PREFIX is /B*CD
Find the third operator: -, take 2 operands before the operator
(/B*CD and A), the PREFIX is -A /B*CD
Exercise: Converting
1. Convert these INFIX to PREFIX and POSTFIX :
a) A / B – C / D
b) (A + B) ^ 3 – C * D
c) A ^ (B + C)
2. Convert these PREFIX to INFIX and POSTFIX :
a) +–/ABC^DE
b) –+DE/XY
c) ^+23–CD
3. Convert these POSTFIX to INFIX and PREFIX :
a) ABC+–
b) GH+IJ/*
c) AB^CD+–
The idea of converting infix to postfix using a stack:
• Example. Convert infix a + b * c to postfix
abc*+.
• We scan the input stream left to right, output each operand as they are
scanned. The main idea is that when encountering an operator, it is
pushed onto the stack if the stack is empty, or if it has a higher
precedence than that of the stack top. Thus, the following chart
demonstrates the snapshots of the input stream vs. the stack and the
output during the conversion process:
next token stack output comments
(Initially) empty none
a empty a always output operand
+ + a push when stack empty
b + ab always output operand
* +* ab push if higher precedence
c +* abc always output operand
(at end) empty abc*+ pop everything off stack
• Another example: Convert infix a*(b + c)/d to postfix
abc+*d/.
• next token stack output comments
• (Initially) empty none
a empty a output operand
* * a push operator if stack empty
( *( a always push (
b *( ab output operand
+ *(+ ab push operator if stack top (
c *(+ abc output operand
) * abc+ pop all operators until (
/ / abc+* pop *, push /
d / abc+*d output operand
(at end) empty abc+*d/ pop everything off stack
• Note that the token ( is pushed onto stack when scanned;
once it is in the stack all operators are considered with a
higher precedence against (. Also, we need to resolve
operators with left or right-associative properties. For
example, a+b+c means (a+b)+c but a^b^c means a^(b^c).
• We define the precedence levels of various operators including
the parentheses, distinguishing whether the operators are
currently inside the stack or they are incoming tokens.
• operator tokens in-stack precedence in-coming
precedence (ISP) (ICP)
) (N/A) (N/A)
^ 3 4
*, / 2 2
+, – 1 1
( 0 4
$ –1 (N/A)
• The idea is that when encountering an in-coming operator, pop
all operators in the stack that have a higher or equal ISP than
the ICP of the new operator, then push the new operator onto
the stack. The initial stack is marked with a “bottom marker”
$ with a –1 precedence, which serves as a sentinel symbol.
Algorithm 6.6:POLISH(Q,P)
suppose Q is an arithmetic expression written in infix
notation . This algorithm finds the equivalent postfix
expression P.
1.push“(” onto STACK, and add “)” to the end of Q.
2.Scan Q from left to right and repeat steps 3 to 6
for each element of Q until the STACK is empty:
3. If an operand is encountered , add it to P.
4. If a left parenthesis is encountered ,push it onto
STACK.
5.If an operator is encountered, then:
(a)repeatedly pop from STACK and add to P each
operator (on the top of STACK) which has the
same precedence as or higher precedence than
operator.
(b) Add operator to STACK.
[End of if structure.]
6. If a right parenthesis is encountered, then:
(a)Repeatedly pop from stack and add to P each
operator (on the top of STACK) until a left
parenthesis is encountered.
(b) Remove the left parenthesis.
[do not add the parenthesis to P.]
[End of If structure.]
[End of step 2 loop.]
7.Exit.
Solve the example
• Q: A + ( B * C – ( D / E ^ F ) * G ) * H
• PUSH ( onto STACK, and then add ) to the end of Q.
SYMBOL SCANNED STACK EXPRESSION P
1. A ( A
2. + ( + A
3. ( ( +( A
4. B ( +( AB
5. * ( +( * AB
6. C ( +( * ABC
7. - ( +( - ABC*
8. ( ( +( - ( ABC*
9. D ( +( - ( ABC *D
10. / ( +( - ( / ABC *D
11. E ( +( - ( / ABC * DE
12. ^ ( +( - ( / ^ ABC * DE
13. F ( +( - ( / ^ ABC * DEF
14. ) ( +( - ABC * DEF ^/
15. * ( +( - * ABC * DEF ^/
16. G ( +( - * ABC * DEF ^/ G
17. ) ( + ABC * DEF ^/ G * -
18. * ( + * ABC * DEF ^/ G * -
19. H ( + * ABC * DEF ^/ G * - H
20. ) ABC * DEF ^/ G * - H * +
Example
• Convert the expression into postfix and
evaluate it
• 2 ^ 3 + 5 * 2 ^ 2 – 12 / 6
• 2 3 ^ 5 2 2 ^ * + 12 6 / -
• Final result 26
QuickSort
• A more efficient exchange sorting scheme than
bubble sort
– A typical exchange involves elements that are far apart
– Fewer interchanges are required to correctly position an
element.
• Quicksort uses a divide-and-conquer strategy
– A recursive approach
– The original problem partitioned into simpler sub-
problems,
– Each sub problem considered independently.
• Subdivision continues until sub problems obtained
are simple enough to be solved directly
QuickSort

• Choose some element called a pivot


• Perform a sequence of exchanges so that
– All elements that are less than this pivot are to its left and
– All elements that are greater than the pivot are to its right.
• Divides the (sub)list into two smaller sub lists,
• Each of which may then be sorted independently in
the same way.
QuickSort
If the list has 0 or 1 elements,
return. // the list is sorted
Else do:
Pick an element in the list to use as the pivot.
Split the remaining elements into two disjoint groups:
SmallerThanPivot = {all elements < pivot}
LargerThanPivot = {all elements > pivot}

Return the list rearranged as:


Quicksort(SmallerThanPivot),
pivot,
Quicksort(LargerThanPivot).
QuickSort
• Given to sort:
44 ,33,11,55,77,90,40,60,99,22,88,66

Select, arbitrarily, the first element, 44, as pivot(LOC)


Search from right for elements <= 44, stop at first element
<=44
Interchange 22 and 44.
• [LOC] 44 ,33,11,55,77,90,40,60,99, 22 ,88,66.[RIGHT]
• [LEFT] 22 ,33,11,55,77,90,40,60,99, 44 [LOC],88,66.

• Search from left for element >=44 stop at element >=44


• Interchange 44 and 55
• 22,33,11,44[LOC],77,90,40,60,99,55[RIGHT],88,66
• 22,33,11,44[LOC],77,90,40,60,99,55[RIGHT],88,66
• Start from right and search for element less than
44,exchange 40 and 44.
• 22,33,11,40[left],77,90,44[loc],60,99,55,88,66
• Start from left and search for element greater than
44,exchange 77 and 44.
• 22,33,11,40,44[loc],90,77[right],60,99,55,88,66.
• Start from right and search for element less than
44. loc and right are overlapped, means two
sublists are created,
• 22,33,11,40, 44, 90,77,60,99,55,88,66
Quick sort
• In above list A with n=12, algorithm begins by pushing boundary
values 1 and 12 onto STACK.
LOWER=1 and UPPER=12
• In order to apply reduction step, it removes the top values 1 and
12 from the stacks, leaving
LOWER=(empty) and UPPER=(empty)
• After reduction step, finally places first ele. 44 in A[5]
• And pushesh the boundary values 1 and 4 of first sublist and 6 and
12 of second sublist.
LOWER=1,6 and UPPER=4,12.
• In order to apply reduction step, Algorithm removes the top
values 6 and 12 from the stack leving
LOWER=1 and UPPER=4
• And then applies the reduction step to the corresponding sublist
A[6],A[7],…………A[12] And so on.

Example:- Apply quick sort 75, 70, 65, 68, 61, 55, 100, 93, 78, 98, 81,
84
QUICKSORT: an application of STACK
• Procedure 6.7: QUICK(A,N,BEG,END,LOC)
Here A is an array with N elements . parameters BEG and END contain the
boundary values of the sub list of A to which this procedure applies.LOC
keeps track of the position of the first element A[BEG] of the sub list during
the procedure . The local variable LEFT and RIGTH will contain the boundary
values of the list of elements that have not been scanned.
1.[Initialize] set LEFT:=BEG,RIGTH:=END and LOC:=BEG.
2.[scan from right to left.]
(a)Repeat while A[LOC]<= A[RIGHT] and
LOC ≠RIGHT:RIGHT:=RIGHT-1.
[End of loop]
(b) If LOC=RIGHT , then : Return.
(c)If A[LOC]>A[RIGTH],then:
I )[Interchange A[LOC] and A[RIGHT].
TEMP:=A[LOC],A[LOC]:=A[RIGHT],
A[RIGHT]:=TEMP.
QUICKSORT
II) Set LOC:=RIGHT.
III)Go to step 3.
[End of If structure.]
3.[scan from left to right]
(a)Repeat while A[LEFT]<=A[LOC] and LEFT != LOC:
LEFT:=LEFT+1.
[End of loop.]
(b)If LOC=LEFT , then : return.
(c)If A[LEFT]>A[LOC],then
I )[interchange A[LEFT] and A[LOC].
TEMP:=A[LOC], A[LOC]:=A[LEFT],A[LEFT]:=TEMP.
II)set LOC:=LEFT.
III)Go to step 2.
[End of If structure.]
Algorithm 6.8: (Quicksort)
• This algorithm sorts an array A with N Elements
1.[Initialize] TOP:=NULL.
2.[Push boundary values of A onto stacks when A has
two or more elements.]
If N>1,then:TOP:=TOP+1,LOWER[1]:=1,UPPER[1]:=N.
3.Repeat step 4 to 7 While TOP =/= NULL.
4. [pop sublist from stacks]
Set BEG:=LOWER[TOP],END:=UPPER[TOP],
TOP:=TOP-1.
5. Call QUICK(A,N,BEG,END,LOC).
[procedure QUICK]
Algorithm 6.8: (Quicksort)
6.[push left sublist onto stacks when it has 2 or more
elements.]
IF BEG<LOC-1,then:
TOP:=TOP+1,LOWER[TOP]:=BEG,
UPPER[TOP]=LOC-1,
[end of if structure]
7.[push right sublist onto stacks when it has two or more
elements.]
If LOC+1< END,then:
TOP:=TOP+1,LOWER[TOP]:=LOC+1,
UPPER[TOP]:=END.
[end of if structure.]
[end of step 3 loop]
8.Exit.
Complexity of Quick sort algorithm
• Worst case complexity
• f(n)=n+(n-1)+(n-2)+---------------+2+1 =n(n+1)/2
=n2 / 2 + O(n)=O(n2).
• Average case Complexity
• f(n)=O(n log n)
On average each reduction step of the algorithm produces two
sublists.
1) Reducing the initial list places 1 element and produces 2 sublist.
2) Reducing the two sub list places 2 element and produces 4
sublist. And so on.
3) Reduction step in kth level finds the location of 2k-1 elements.
4) Approximately log2n levels of reduction steps.
5) Each level uses at most n comparisons, so f(n)=O(n log n)
Recursion
• What is recursion?
• Sometimes, the best way to solve a problem is
by solving a smaller version of the exact same
problem first
• Recursion is a technique that solves a problem
by solving a smaller problem of the same type
Recursion
• Some computer programming languages allow
a module or function to call itself. This
technique is known as recursion.
• In recursion, a function α either calls itself
directly or calls a function β that in turn calls
the original function α. The function α is
called recursive function
Recursion
• Properties
• A recursive function can go infinite like a loop. To
avoid infinite running of recursive function, there
are two properties that a recursive function must
have −
• Base criteria − There must be at least one base
criteria or condition, such that, when this
condition is met the function stops calling itself
recursively.
• Progressive approach − The recursive calls should
progress in such a way that each time a recursive
call is made it comes closer to the base criteria.
When you turn this into a program, you end up with
functions that call themselves (recursive functions)
int f(int x)
{
int y;

if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
Problems defined recursively
• There are many problems whose solution can
be defined recursively
Example: n factorial
1 if n = 0
n!= (recursive solution)
(n-1)!*n if n > 0

1 if n = 0
n!= (closed form solution)
1*2*3*…*(n-1)*n if n > 0
Coding the factorial function
• Recursive implementation

int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

Compute 5!

L16 53
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

f(5)=
5·f(4)

L16 54
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

f(4)= f(5)=
4·f(3) 5·f(4)

L16 55
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

f(3)= f(4)= f(5)=


3·f(2) 4·f(3) 5·f(4)

L16 56
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

f(2)= f(3)= f(4)= f(5)=


2·f(1) 3·f(2) 4·f(3) 5·f(4)

L16 57
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

f(1)= f(2)= f(3)= f(4)= f(5)=


1·f(0) 2·f(1) 3·f(2) 4·f(3) 5·f(4)

L16 58
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

1·1= f(2)= f(3)= f(4)= f(5)=


1→ 2·f(1) 3·f(2) 4·f(3) 5·f(4)

L16 59
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

2·1= f(3)= f(4)= f(5)=


2→ 3·f(2) 4·f(3) 5·f(4)

L16 60
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

3·2= f(4)= f(5)=


6→ 4·f(3) 5·f(4)

L16 61
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

4·6= f(5)=
24→ 5·f(4)

L16 62
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

5·24=
120→

L16 63
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}

Return 5!
= 120

L16 64
Recursive Definition for Fibonacci
If n=0 or n=1, then Fn =n

If n >1, then Fn= Fn-2 + Fn-1


Recursive function for Fibonacci
• A procedure for finding the nth term Fn of
the Fibonacci sequence
• FIBONACCI(FIB,N)
• If N=0 or N=1 then: Set FIB:=N, and Return
• Call FIBONACCI(FIBA,N-2)
• Call FIBONACCI(FIBB,N-1)
• Set FIB:= FIBA + FIBB
• Return
example
void printFun(int test)
{ if (test < 1)
return;
else
{ cout << test << " ";
printFun(test-1); // statement 2
cout << test << " ";
return;
}
}
int main()
{
int test = 3;
printFun(test);
}
the memory stack has been shown in
below diagram.
example
void fun1(int n){
if(n == 0) return;
printf(“%d”, n);
fun2(n-2);
printf(“%d”, n);
}
void fun2(int n){
if(n == 0) return;
printf(“%d”, n);
fun1(++n);
printf(“%d”, n); }
The output printed when fun1 (5) is called is
(A) 53423122233445 (B) 53423120112233
(C) 53423122132435 (D) 53423120213243
How is recursion implemented?
• What happens when a function gets called?
int a(int w)
{
return w+w;
}

int b(int x)
{
int z,y;
……………… // other statements
z = a(x) + y;
return z;
}
What happens when a function is called?
(cont.)
• An activation record is stored into a stack
(run-time stack)
1) The computer has to stop executing
function b and starts executing function a
2) Since it needs to come back to function b
later, it needs to store everything about
function b that is going to need (x, y, z,
and the place to start executing upon
return)
3) Then, x from a is bounded to w from b
4) Control is transferred to function a
What happens when a
function is called? (cont.)
• After function a is executed, the activation
record is popped out of the run-time stack
• All the old values of the parameters and
variables in function b are restored and the
return value of function a replaces a(x) in the
assignment statement
What happens when a recursive
function is called?
• Except the fact that the calling and called functions have the
same name, there is really no difference between recursive
and nonrecursive calls
int f(int x)
{
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
The Towers of Hanoi
A Stack-based Application
– GIVEN: three poles
– a set of discs on the first pole, discs of different sizes, the smallest
discs at the top
– GOAL: move all the discs from the left pole to the right one.
– CONDITIONS: only one disc may be moved at a time.
– A disc can be placed either on an empty pole or on top of a larger disc.
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
• For n>1 disc may be reduced to the following
sub problems
• Move top n-1 disc from peg A to Peg B
• Move the top disc from peg A to Peg C
• Move top n-1 disc from peg B to Peg C
• The solution may be reduced to the solution
of the following three sub problems
TOWER(N-1,BEG,END,AUX)
TOWER(1,BEG,AUX,END) OR BEG→END
TOWER(N-1, AUX, BEG,END)
Tower of Hanoi algorithm
• Procedure TOWER(N,BEG,AUX,END)
1.If N=1 then:
Write: BEG-> END.
Return.
[end of if structure]
2.Call TOWER(N-1,BEG,END,AUX)
3.Write: BEG-> END.
4. Call TOWER(N-1, AUX, BEG,END)
5.return.
• Moves for 3 disc
• Move disk 1 from A → C
• Move disk 2 from A → B
• Move disk 1 from C → B
• Move disk 3 from A → C
• Move disk 1 from B → A
• Move disk 2 from B → C
• Move disk 1 from A → C
• The time complexity of an algorithm is
• f(n)=2n -1 moves for n disc
• Draw schematic diagram for n =4
Examples(HomeWork)
Suppose S is string with N character. Let SUB(S,J,L) denote
the substring of S beginning in the position J and
length L.
Let A//B denote concatenation of strings A and B.
Suppose REV(S,N) is recursively defined by
REV(S,N) =S if N=1
REV(S,N)=SUB(S,N,1)//REV(SUB(S,1,N-1) otherwise
Find REV(S,N) when
N=3, S=abc
N=5, S=ababc
Cont….
Which best describes what the printString function
below does
public void printString(String s)
{ if (s.length() > 0)
{ printString(s.substring(1));
System.out.print(s.substring(0,1));
} }
A) It prints string s
B) It prints string s in reverse order
C) It prints only the first character of string S
D) it prints only the last character of string S
Cont….
1)Let n denote a positive integer .Suppose function
L is recursively defined as
0 if n=1
L(n)= L(“floor of “(n/2)+1) if n>1
Find L(25) what this function do?
2) Let A be an integer array with N elements.
Suppose X is an integer function defined by
0 if K=0
X(K)=X(A,N,K)= X(K-1)+A(K) if 0<K<=N
X(K-1) if K>N
Find X(5) for N=8 A:3,7,-2,5,6,-4,2,7
Cont….
1) Predict the output of following program. What does the following fun() do in
general?
int fun(int a, int b)
{
if (b == 0)
return 0;
if (b % 2 == 0)
return fun(a+a, b/2);
return fun(a+a, b/2) + a;
}
int main()
{
printf("%d", fun(4, 3));
getchar();
return 0;
}
• Output: 12
• It calulates a*b (a multipied b).

You might also like