Sie sind auf Seite 1von 3

EXAMPLES OF RECURSION

• Towers of Hanoi
• Writing Linked Lists Backwards
• Recursive Insert
• 8 Queens
• Recognizing Simple Languages Peg A Peg B Peg C
• Prefix Expressions
• Conversion Prefix to Postfix
1 2

How do we transfer all disks from A to C, The solution is simple and recursive:
with the following limitations:
Basic idea:
1) Only one disk at a time may be moved. 1) Transfer recursively all but the largest disk
2) A larger disk may never lie on a smaller from A to the temporary peg B.
disk. 2) Transfer the largest disk from A to C.
3) Transfer recursively all disks from B to C.

3 4

void tow (int cnt, char src, char dst, char spr)
{
NOTE: While you are transferring n-1 disks if (cnt = = 1)
from A to B, you are using C as a “temporary cout << src << “ --> “ << dst << endl;
storage”. While you are transferring n-1 disks else {
from B to C, you are using A as a temporary tow (cnt-1, src, spr, dst);
storage. tow (1, src, dst, spr);
tow (cnt-1, spr, dst, src);
That’s it. It is that simple. }
}
5 6
EXAMPLE: NOTE: This would work with 3 pegs, even if
there are 4, 5, 6, 7, ... disks! (the pegs just
1 1 have to be higher. 8-) :-) ).
2 2 1 1 2 2
3 31 312 3 2 32 132 13 3 The solution is completely general.
ABC ABC ABC ABC ABC ABC ABC ABC

7 8

struct str {
char data;
struct str *next;
Writing Linked Lists Backward (recursively) };

This is very hard iteratively. Try it! void writeback(struct str *ptr)
It’s very easy recursively. {
if (str != NULL) {
writeback (str next);
cout << str data << endl;
}
9 } 10

Assume that data is now a single character! Insert Revisited


head
We will now redo “insert into sorted linked
C A T NULL
list”. This time recursively. It turns out that
this is simpler than iterative insert.
writeback(head);

str str str str

11 12
void Insert (struct node *L, int X)
{ EXAMPLE:
if ((L = = NULL) || (X < L data)) {
struct node *p = new node; head
p data = X; 4 8 12
p next = L;
L = p;
} X 10
else Insert (L next, X)
} 13 14

EXAMPLE:

head
4 8 12

X 2

15

Das könnte Ihnen auch gefallen