12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

132 Chap. 4 Lists, Stacks, <strong>and</strong> Queuesstatic void TOH(int n, Pole start,Pole goal, Pole temp) {// Make a stack just big enoughStack S = new AStack(2*n+1);S.push(new TOHobj(operation.TOH, n,start, goal, temp));while (S.length() > 0) {TOHobj it = S.pop(); // Get next taskif (it.op == operation.MOVE) // Do a movemove(it.start, it.goal);else if (it.num > 0) { // Imitate TOH recursive// solution (in reverse)S.push(new TOHobj(operation.TOH, it.num-1,it.temp, it.goal, it.start));S.push(new TOHobj(operation.MOVE, it.start,it.goal)); // A move <strong>to</strong> doS.push(new TOHobj(operation.TOH, it.num-1,it.start, it.temp, it.goal));}}}We first define an enumerated type called TOHop, with two valuesMOVE <strong>and</strong> TOH, <strong>to</strong> indicate calls <strong>to</strong> the move function <strong>and</strong> recursive calls<strong>to</strong> TOH, respectively. Note that an array-based stack is used, because weknow that the stack will need <strong>to</strong> s<strong>to</strong>re exactly 2n + 1 elements. The newversion of TOH begins by placing on the stack a description of the initialproblem of n rings. The rest of the function is simply a while loop thatpops the stack <strong>and</strong> executes the appropriate operation. In the case of a TOHoperation (for n > 0), we s<strong>to</strong>re on the stack representations for the threeoperations executed by the recursive version. However, these operationsmust be placed on the stack in reverse order, so that they will be popped offin the correct order.Some “naturally recursive” applications lend themselves <strong>to</strong> efficient implementationwith a stack, because the amount of information needed <strong>to</strong> describe a subproblemis small. For example, Section 7.5 discusses a stack-based implementationfor Quicksort.4.3 QueuesLike the stack, the queue is a list-like structure that provides restricted access <strong>to</strong>its elements. Queue elements may only be inserted at the back (called an enqueue

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!