(双栈模拟数组) 只使用两个栈结构 stack1 和
(双栈模拟数组) 只使用两个栈结构 stack1 和 stack2,模拟对数组的随机读取。作为栈 结构, stack1 和 stack2 只能访问栈顶 (最后一个有效元素) 。栈顶指针 top1 和 top2 均指向栈 顶元素的下一个位置。 输入第一行包含的两个整数,分别是数组长度 n 和访问次数 m,中间用单个空格隔开。 第二行包含 n 个整数,一次歌出数组各项(数组下标从 0 到 a-1)。第三行包含 m 个整数, 需要访问的数组下标。对于每次访问,输出对应的数组元素。
#include <iostream>
using namespace std;
const int SIZE = 100;
int stack1[SIZE], stack2[SIZE];
int top1, top2;
int n, m, i, j;
void clearStack(){
int i;
for(i = top1; i < SIZE; i++)
stack1[i] = 0;
for(i = top2; i < SIZE; i++)
stack2[i] = 0;
}
int main(){
cin >> n >>m;
for(i = 0; i < n; i++)
cin >> stack1[i];
top1 = ①;
top2 = ②;
for(j = 0; j < m; j++){
cin >> i;
while (i < top1 - 1){
top1--;
③;
top2++;
}
while(i > top1 - 1){
top2--;
④;
top1++;
}
clearStack();
cout << stack1[⑤] << endl;
}
return 0;
}答案
第1空:n
第2空:0
第3空:stack2[top2] = stack1[top1]
第4空:stack1[top1] = stack2[top2]
第5空:top1 - 1