编程题

(双栈模拟数组)只使用两个栈结构stack1和stack2,模拟对数组的随机读取。作为栈结构,stack1和stack2只能访问栈顶(最后一个有效元素)。栈顶指针top1和top2均指向栈顶元素的下一个位置。

输入第一行包含两个整数,分别是数组长度n和访问次数m,中间用单个空格隔开。

第二行包含n个整数,依次给出数组各项(数组下标从0到n-1)。第三行包含m个整数,需要访问的数组下标。对于每次访问,输出对应的数组元素。(前两空每空2.5分,其余每空3分,共14分)

#include

using namespace std;


const int SIZE = 100;


int stack1[SIZE], stack2[SIZE];

int top1, top2;

int n, m, i, j;


void clearStack() {

\tint i;

\tfor (i = top1; i < SIZE; i )

\t\tstack1[i] = 0;

\tfor (i = top2; i < SIZE; i )

\t\tstack2[i] = 0;

}

int main() {

\tcin >> n >> m;

\tfor (i = 0; i < n; i )

\t\tcin >> stack1[i];

\ttop1 = (1) ;

\ttop2 = (2) ;

\tfor (j = 0; j < m; j ) {

\t\tcin >> i;

\t\twhile (i < top1 - 1) {

\t\t\ttop1--;

\t\t (3) ;

\t\t\ttop2 ;

\t\t}

\t\twhile (i > top1 - 1) {

\t\t\ttop2--;

\t\t\t (4) ;

\t\t\ttop1 ;

\t\t}

\t\tclearStack();

\t\tcout << stack1[ (5) ] << endl;

\t}

\treturn 0;

}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论