-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTower.java
46 lines (38 loc) · 986 Bytes
/
Tower.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package org.blueocean;
import java.util.Stack;
public class Tower{
final Stack<Integer> stack;
int index;
Tower(int n){
index = n;
stack = new Stack<Integer>();
}
public void addTop(int disk){
if(disk<=0)
throw new IllegalArgumentException("arg has to be positive" + disk);
else if(!stack.isEmpty() && disk >= peekTop()){
throw new IllegalArgumentException("arg has to be valid" + disk + peekTop());
}else{
stack.push(disk);
}
}
public Integer peekTop(){
return stack.peek();
}
public Integer removeTop(){
return stack.pop();
}
private void moveTop(Tower dest){
dest.addTop(removeTop());
}
public void moveTower(Tower dest, Tower buffer, int numOfDisk){
if(numOfDisk==0)
return;
this.moveTower(buffer, dest, numOfDisk-1);
System.out.println(numOfDisk-1 + "before");
moveTop(dest);
System.out.println("moveTop");
buffer.moveTower(dest, this, numOfDisk-1);
System.out.println(numOfDisk-1);
}
}