最近写了几个递归的程序.
1.
汉诺塔 定义: http://baike.baidu.com/view/191666.htm
程序:
1package interative;
2
3import java.util.Stack;
4
5public class Hanoi {
6
7 public static Stack<Integer> source = new Stack<Integer>();
8 public static Stack<Integer> temp = new Stack<Integer>();
9 public static Stack<Integer> dest = new Stack<Integer>();
10
11 public static void main(String[] args) {
12 Hanoi hanoi = new Hanoi(4);
13 hanoi.print();
14 hanoi.move(hanoi.discNumber);
15 }
16
17 private int discNumber = 3;
18
19 public Hanoi() {
20 this(3);
21 }
22
23 public Hanoi(int discNumber) {
24 for (int i = discNumber; i > 0; i--) {
25 source.push(i);
26 }
27
28 this.discNumber = discNumber;
29
30 }
31
32 public int getDiscNumber() {
33 return discNumber;
34 }
35
36 public void setDiscNumber(int discNumber) {
37 this.discNumber = discNumber;
38 }
39
40 private void move(int number) {
41 move(number, source, temp, dest);
42 }
43
44 private void move(int number, Stack<Integer> source, Stack<Integer> temp,
45 Stack<Integer> dest) {
46 if (number == 1) {
47 dest.push(source.pop());
48 print();
49 } else {
50 move(number - 1, source, dest, temp);
51 dest.push(source.pop());
52 print();
53 move(number - 1, temp, source, dest);
54 }
55 }
56
57 private void print() {
58 System.out.print("Port A: ");
59 for (Integer disc : source) {
60 System.out.print(disc + " ");
61 }
62 System.out.println();
63
64 System.out.print("Port B: ");
65 for (Integer disc : temp) {
66 System.out.print(disc + " ");
67 }
68 System.out.println();
69
70 System.out.print("Port C: ");
71 for (Integer disc : dest) {
72 System.out.print(disc + " ");
73 }
74 System.out.println();
75 System.out.println();
76 }
77
78}
程序输出:
Port A: 4 3 2 1
Port B:
Port C:
Port A: 4 3 2
Port B: 1
Port C:
Port A: 4 3
Port B: 1
Port C: 2
Port A: 4 3
Port B:
Port C: 2 1
Port A: 4
Port B: 3
Port C: 2 1
Port A: 4 1
Port B: 3
Port C: 2
Port A: 4 1
Port B: 3 2
Port C:
Port A: 4
Port B: 3 2 1
Port C:
Port A:
Port B: 3 2 1
Port C: 4
Port A:
Port B: 3 2
Port C: 4 1
Port A: 2
Port B: 3
Port C: 4 1
Port A: 2 1
Port B: 3
Port C: 4
Port A: 2 1
Port B:
Port C: 4 3
Port A: 2
Port B: 1
Port C: 4 3
Port A:
Port B: 1
Port C: 4 3 2
Port A:
Port B:
Port C: 4 3 2 1
2. 二叉树
待续