11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

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

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

124 Chap. 4 Lists, Stacks, <strong>and</strong> Queuespublic enum oper<strong>at</strong>ion { MOVE, TOH }class TOHobj {public oper<strong>at</strong>ion op;public int num;public Pole start, goal, temp;}/** Recursive call oper<strong>at</strong>ion */TOHobj(oper<strong>at</strong>ion o, int n, Pole s, Pole g, Pole t){ op = o; num = n; start = s; goal = g; temp = t; }/** MOVE oper<strong>at</strong>ion */TOHobj(oper<strong>at</strong>ion o, Pole s, Pole g){ op = o; start = s; goal = g; }st<strong>at</strong>ic 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(oper<strong>at</strong>ion.TOH, n,start, goal, temp));while (S.length() > 0) {TOHobj it = S.pop(); // Get next taskif (it.op == oper<strong>at</strong>ion.MOVE) // Do a movemove(it.start, it.goal);else if (it.num > 0) { // Imit<strong>at</strong>e TOH recursive// solution (in reverse)S.push(new TOHobj(oper<strong>at</strong>ion.TOH, it.num-1,it.temp, it.goal, it.start));S.push(new TOHobj(oper<strong>at</strong>ion.MOVE, it.start,it.goal)); // A move to doS.push(new TOHobj(oper<strong>at</strong>ion.TOH, it.num-1,it.start, it.temp, it.goal));}}}Figure 4.23 Stack-based implement<strong>at</strong>ion for Towers of Hanoi.move oper<strong>at</strong>ion actually needs only to store inform<strong>at</strong>ion about two poles.Thus, there are two constructors: one to store the st<strong>at</strong>e when imit<strong>at</strong>ing arecursive call, <strong>and</strong> one to store the st<strong>at</strong>e for a move oper<strong>at</strong>ion.An array-based stack is used because we know th<strong>at</strong> the stack will needto store exactly 2n+1 elements. The new version of TOH begins by placingon the stack a description of the initial problem for n rings. The rest ofthe function is simply a while loop th<strong>at</strong> pops the stack <strong>and</strong> executes theappropri<strong>at</strong>e oper<strong>at</strong>ion. In the case of a TOH oper<strong>at</strong>ion (for n > 0), westore on the stack represent<strong>at</strong>ions for the three oper<strong>at</strong>ions executed by therecursive version. However, these oper<strong>at</strong>ions must be placed on the stackin reverse order, so th<strong>at</strong> they will be popped off in the correct order.

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

Saved successfully!

Ooh no, something went wrong!