Skip to content

Commit

Permalink
Create Q3_4
Browse files Browse the repository at this point in the history
  • Loading branch information
donnice committed Jul 4, 2014
1 parent 6c2f4e0 commit f36f19e
Showing 1 changed file with 105 additions and 0 deletions.
105 changes: 105 additions & 0 deletions Q3_4
@@ -0,0 +1,105 @@
import java.util.*;
class Stacks{
int[] stElem;
int top;

public Stacks(int maxSize){
stElem = new int[maxSize];
top = 0;
}

public int pop(){
if(top == 0)
return 0;
else
return stElem[--top];
}

public void push(int e){
if(top == stElem.length)
System.out.println("栈已满!");
else
stElem[top++] = e;
}

public int displayTop(){
if(top == 0)
return 0;
else
return stElem[top-1];
}

public void display(){
for(int i = top-1; i>=0; i--)
System.out.print(stElem[i]+" ");
System.out.println();
}

}
public class Q3_4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入汉诺塔盘数:");
int n = sc.nextInt();
Stacks st1 = new Stacks(n);
Stacks st2 = new Stacks(n);
Stacks st3 = new Stacks(n);
for(int i =n-1; i>=0; i--)
st1.push(i+1);
st1.display();
int c = 0;
int k = 0;
int m = 1<<n;
int t;
while(k < m-1){
switch((c+1)%3){
case 0: st1.push(st3.pop());
break;
case 1: st2.push(st1.pop());
break;
case 2: st3.push(st2.pop());
break;
}
k++;
if(k != m-1){
switch((c+1)%3){
case 0: if(st3.top == 0)
st3.push(st2.pop());
else if(st2.top == 0)
st2.push(st3.pop());
else if(st3.displayTop()>st2.displayTop())
st3.push(st2.pop());
else
st2.push(st3.pop());
break;
case 1: if(st3.top == 0)
st3.push(st1.pop());
else if(st1.top == 0)
st1.push(st3.pop());
else if(st3.displayTop()>st1.displayTop())
st3.push(st1.pop());
else
st1.push(st3.pop());
break;
case 2: if(st1.top == 0)
st1.push(st2.pop());
else if(st2.top == 0)
st2.push(st1.pop());
else if(st1.displayTop()>st2.displayTop())
st1.push(st2.pop());
else
st2.push(st1.pop());
break;
}
k++;
c++;
}
else
break;
}

st1.display();
st2.display();
st3.display();
}
}

0 comments on commit f36f19e

Please sign in to comment.