An example of Hanoi Tower code in JAVA data structure
- 2021-07-16 02:20:43
- OfStack
In this paper, we share the specific code of Hanoi Tower of JAVA data structure for your reference. The specific contents are as follows
package p02. Dynamic linked list ;
import p01. Dynamic array .Stack;
public class LinkedStack<E> implements Stack<E> {
private LinkedList<E> list;
public LinkedStack(){
list=new LinkedList<>();
}
@Override
public void push(E e) {
// TODO Automatically generated method stubs
list.addFrist(e);
}
@Override
public E pop() {
// TODO Automatically generated method stubs
return list.removeFrist();
}
@Override
public boolean isEmpty() {
// TODO Automatically generated method stubs
return list.isEmpty();
}
@Override
public E peek() {
// TODO Automatically generated method stubs
return list.getFrist();
}
@Override
public int getSize() {
// TODO Automatically generated method stubs
return list.getSize();
}
@Override
public void clear() {
// TODO Automatically generated method stubs
list.clear();
}
@Override
public String toString() {
// TODO Automatically generated method stubs
return list.toString();
}
}
// Realize the Tower of Hanoi with the chain stack realized above
package p03. Recursion ;
import p02. Dynamic linked list .LinkedStack;
public class Hano {
public static void main(String[] args) {
// String x = "x"; // Original disk
// String y = "y"; // With the aid of disk
// String z = "z"; // Final disk
// 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);
}
// Definition 3 Stack to realize its movement
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);
}
}
// Print only the movement process.
/*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);
}*/
}