Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the classic problem of the Towers of Hanoi, you have three towers and N disks

ID: 3857309 • Letter: I

Question

In the classic problem of the Towers of Hanoi, you have three towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e. each disk sits on top of an even larger one). You have the following constraints: a. Only one disk can be moved at a time. b. A disk is slid off the top of one of the tower onto the next tower. c. A disk can only be placed on top of a larger disk. What will be the algorithm (logic) to move the disks from first tower to the last using stacks? The stack supports the following operations: push, pop, peek, isEmpty. Write the algorithm (logic) to sort a stack in ascending order (with the biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, isEmpty.

Explanation / Answer

The general algorithm for moving N disks from tower number 1 to tower number 3 would be

Pseudo code will be:

void solve( N, stack_1, stack_2, stack_3 ) {
   if N == 1 {
item = stack_1.pop
   stack_3.push(item)
} else {
   solve( N-1, stack_1, stack_3, stack_2 )
solve( 1, stack_1, stack_2, stack_3 )
   solve( N-1, stack_2, stack_1, stack_3 )
   }
}