数据结构模拟 数据结构学的还是不扎实 参考了大神的思路。
把问题分开细化,然后再整合会吧复杂的问题简单化,思路也就不乱了。
直接上代码 (Java):
import java.util.*;
public class Main101 {
public static int[] place = new int[25];
public static int[][] stack = new int[25][25];
public static int[] top = new int[25];
public static int[] temp = new int[25];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size;
String str1,str2;
int[] res = new int[30];
while(scan.hasNext()) {
int a,b;
size = scan.nextInt();
for ( int i = 0 ; i < size ; ++ i ) {
stack[i][0] = i;
place[i] = i;
top[i] = 0;
}
while(true) {
str1 = scan.next();
if(str1.equals("quit"))break;
a = scan.nextInt();
str2 = scan.next();
b = scan.nextInt();
if(place[a] == place[b])continue;
if(str1.equals("move")) {
pushback(a);
}
if(str2.equals("onto")) {
pushback(b);
}
move(a, b);
}
for(int i=0; i<size; i++) {
System.out.print(i + ":");
int cur = 0;
while(cur <= top[i]) {
System.out.print(" " + stack[i][cur++]);
}
System.out.println();
}
}
}
public static void pushback(int a) {
int block,id = place[a];
while(stack[id][top[id]] != a) {
block = stack[id][top[id] --];
place[block] = block;
stack[block][++ top[block]] = block;
}
}
public static void move(int a, int b) {
int topt = -1,id = place[a],ID = place[b];
while ( stack[id][top[id]] != a )
temp[++ topt] = stack[id][top[id] --];
place[a] = ID;
stack[ID][++ top[ID]] = a;
top[id] --;
while ( topt >= 0 ) {
place[temp[topt]] = ID;
stack[ID][++ top[ID]] = temp[topt --];
}
}
}