Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
105 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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(); | ||
} | ||
} |