class Stack:
package hanoi;
public class Stack {
private String name;
private int[] data;
private int size;
private int top;
public Stack() {
}
public Stack(String name, int[] data, int size, int top) {
this.name = name;
this.data = data;
this.size = size;
this.top = top;
}
public int[] getData() {
return data;
}
public void setData(int[] data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public void push(int item) {
if (top == size) {
} else {
data[top] = item;
System.out.println("Push " + item + " to " + name);
top++;
}
}
public void pop() {
if (top == 0) {
} else {
System.out.println("Pop " + data[top - 1] + " from " + name);
top--;
}
}
public int getTopStack() {
int topStack = 0;
if (top != 0) {
topStack = data[top - 1];
}
return topStack;
}
}
class Main
package hanoi;
public class Main {
static void printData(Stack s) {
System.out.print(s.getName() + ": ");
for (int x = 0; x < s.getTop(); x++) {
System.out.print(s.getData()[x] + " ");
}
System.out.println("");
}
static void move(Stack from, Stack to) {
int willMove = from.getTopStack();
from.pop();
to.push(willMove);
}
static void leftToRight(Stack from, Stack to, Stack temp) {
System.out.println("");
while (from.getTop() != 0) {
if (from.getTopStack() > temp.getTopStack() && temp.getTop() == 1) {
break;
} else {
if (to.getTop() == 0 || to.getTopStack() > from.getTopStack()) {
move(from, to);
} else {
move(from, temp);
rightToLeft(from, to, temp);
}
}
}
if (temp.getTop() > 0) {
move(temp, from);
}
}
static void rightToLeft(Stack from, Stack to, Stack temp) {
System.out.println("");
while (to.getTop() != 0) {
if (to.getTopStack() > temp.getTopStack() && temp.getTop() == 1) {
break;
} else {
if (from.getTop() == 0 || from.getTopStack() > to.getTopStack()) {
move(to, from);
} else {
move(to, temp);
leftToRight(from, to, temp);
}
}
}
if (temp.getTop() > 0) {
move(temp, to);
}
}
static void hanoi(Stack from, Stack to, Stack temp) {
while (to.getTop() != to.getSize()) {
leftToRight(from, to, temp);
if (from.getSize() == 0 && temp.getSize() == 0) {
break;
}
System.out.println("==============================");
printData(from);
printData(temp);
printData(to);
System.out.println("==============================");
}
}
public static void main(String[] args) {
int size = 4;
Stack s1 = new Stack("Tower 1", new int[size], size, 0);
Stack s2 = new Stack("Tower 2", new int[size], size, 0);
Stack s3 = new Stack("Tower 3", new int[size], size, 0);
s1.push(4);
s1.push(3);
s1.push(2);
s1.push(1);
hanoi(s1, s3, s2);
}
}