组合题6 个小题
已作答 0 / 6
2.(新壳栈)小 Z 设计了一种新的数据结构“新壳栈”。首先,它和传统的栈一样支持压入、弹出操作。此外,其栈顶的前 c 个元素是它的壳,支持翻转操作。其中,c>2 是一个固定的正整数,表示壳的厚度。小 Z 还希望,每次操作,无论是压入、弹出还是翻转,都仅用与 c 无关的常数时间完成。聪明的你能帮助她编程实现“新壳栈”吗?
程序期望的实现效果如以下两表所示。其中,输入的第一行是正整数 c,之后每行输入都是一条指令。另外,如遇弹出操作时栈为空,或翻转操作时栈中元素不足 c 个,应当输出相应的错误信息。
1#include < iostream >2using namespace std;3const int4NSIZE = 100000,5CSIZE = 1000;6int n, c, r, tail, head, s[NSIZE], q[CSIZE];7//数组 s 模拟一个栈,n 为栈的元素个数8//数组 q 模拟一个循环队列,tail 为队尾的下标,head 为队头的下标9bool direction, empty;10int previous(int k) {11 if (direction)12 return ((k + c - 2) % c) + 1;13 else14 return (k % c) + 1;15}16int next(int k) {17 if (direction)18 ①;19 else20 return ((k + c - 2) % c) + 1;21}22void push() {23 int element;24 cin >> element;25 if (next(head) == tail) {26 n++;27 ②;28 tail = next(tail);29 }30 if (empty)31 empty = false;32 else33 head = next(head);34 ③ = element;35}36void pop() {37 if (empty) {38 cout << "Error: the stack is empty!" << endl; return;39 }40 cout << ④ << endl;41 if (tail == head)42 empty = true;43 else {44 head = previous(head);45 if (n > 0) {46 tail = previous(tail);47 ⑤ = s[n];48 n--;49 }50}51}52void reverse() {53 int temp;54 if ( ⑥ == tail) {55 direction = ! direction;56 temp = head;57 head = tail;58 tail = temp;59 }60 else61 cout << "Error: less than " << c << " elements in the stack!" << endl;62}63int main() {64 cin >> c;65 n = 0;66 tail = 1;67 head = 1;68 empty = true;69 direction = true;70 do {71 cin >> r;72 switch (r) {73 case 1:push(); break;74 case 2:pop(); break;75 case 3:reverse(); break;76 }77 }while (r != 0);78 return 0;79}①处应填( )