好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JAVA数据结构之汉诺塔代码实例

本文实例为大家分享了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 p02.动态链表;

 

import p01.动态数组.stack;

 

public class linkedstack<e> implements stack<e> {

     private linkedlist<e> list;

     public linkedstack(){

         list= new linkedlist<>();

     }

     @override

     public void push(e e) {

         // todo 自动生成的方法存根

         list.addfrist(e);

     }

     @override

     public e pop() {

         // todo 自动生成的方法存根

         return list.removefrist();

     }

     @override

     public boolean isempty() {

         // todo 自动生成的方法存根

         return list.isempty();

     }

     @override

     public e peek() {

         // todo 自动生成的方法存根

         return list.getfrist();

     }

     @override

     public int getsize() {

         // todo 自动生成的方法存根

         return list.getsize();

     }

     @override

     public void clear() {

         // todo 自动生成的方法存根

         list.clear();

     }

     @override

     public string tostring() {

         // todo 自动生成的方法存根

         return list.tostring();

     }

    

}

?

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

47

48

49

50

51

//用前边实现的链栈去实现汉诺塔

package p03.递归;

 

import p02.动态链表.linkedstack;

 

public class hano {

     public static void main(string[] args) {

        

//      string x = "x"; //原始盘

//      string y = "y"; //借助盘

//      string z = "z"; //最终盘

//      move(x,y,z,n);

         int n= 10 ;

         linkedstack<integer> stackx= new linkedstack();

         for ( int i=n;i>= 1 ;i--){

             stackx.push(i);

         }

         linkedstack<integer> stacky= new linkedstack();

         linkedstack<integer> stackz= new linkedstack();

        

         move(stackx,stacky,stackz,n);

        

         system.out.println(stackx);

         system.out.println(stackz);

 

     }

     //定义三个栈,实现其移动

     public static void move(linkedstack<integer> x,linkedstack<integer> y, linkedstack<integer> z, int level) {

        

         if (level== 1 ){

             z.push(x.pop());

         } else {

             move(x,z,y,level- 1 );

             z.push(x.pop());

             move(y,x,z,level- 1 );

         }

        

     }

     //只打印移动过程。

     /*public static void move(string x, string y, string z, int level) {

         if(level==1){

             system.out.println(x+"->"+z);

             return;

         }

         move(x,z,y,level-1);

         system.out.println(x+"->"+z);

         move(y,x,z,level-1);

        

     }*/

 

}

以上所述是小编给大家介绍的java数据结构之汉诺塔详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

查看更多关于JAVA数据结构之汉诺塔代码实例的详细内容...

  阅读:11次