(新壳栈)小 Z 设计了一种新的数据结构“新壳栈”。首先,它和传统的栈一样支持压入、弹出操作。此外,其栈顶的前 c 个元素是它的壳,支持翻转操作。其中,c > 2 是一个固定的正整数,表示壳的厚度。小 Z 还希望,每次操作,无论是压入、弹出还是翻转,都仅用与 c 无关的常数时间完成。聪明的你能帮助她编程实现“新壳栈”吗?
程序期望的实现效果如以下两表所示。其中,输入的第一行是正整数 c,之后每行输入都是一条指令。另外,如遇弹出操作时栈为空,或翻转操作时栈中元素不足 c 个,应当输出相应的错误信息。
#include
using namespace std;
const int
\tNSIZE = 100000,
\tCSIZE = 1000;
int n, c, r, tail, head, s[NSIZE], q[CSIZE];
//数组 s 模拟一个栈,n 为栈的元素个数
//数组 q 模拟一个循环队列,tail 为队尾的下标,head 为队头的下标
bool direction, empty;
int previous(int k)
{
\tif (direction)
\t\treturn ((k c - 2) % c) 1;
\telse
\t\treturn (k % c) 1;
}
int next(int k)
{
\tif (direction)
\t ① ;
\telse
\t\treturn ((k c - 2) % c) 1;
}
void push()
{
\tint element;
\tcin>>element;
\tif (next(head) == tail) {
\t\tn ;
\t ② ;
\t\ttail = next(tail);
\t}
\tif (empty)
\t\tempty = false;
\telse
\t\thead = next(head);
\t ③ = element;
}
void pop()
{
\tif (empty) {
\t\tcout<<"Error: the stack is empty!"<
\t\treturn;
\t}
\tcout<< ④ <
\tif (tail == head)
\t\tempty = true;
\telse {
\t\thead = previous(head);
\t\tif (n > 0) {
\t\t\ttail = previous(tail);
\t\t ⑤ = s[n];
\t\t\tn--;
\t\t}
\t}
}
void reverse()
{
\tint temp;
\tif ( ⑥ == tail) {
\t\tdirection = !direction;
\t\ttemp = head;
\t\thead = tail;
\t\ttail = temp;
\t}
\telse
\t\tcout<<"Error: less than "<
}
int main()
{
\tcin>>c;
\tn = 0;
\ttail = 1;
\thead = 1;
\tempty = true;
\tdirection = true;
\tdo {
\t\tcin>>r;
\t\tswitch (r) {
\t\t\tcase 1: push(); break;
\t\t\tcase 2: pop(); break;
\t\t\tcase 3: reverse(); break;
\t\t}
\t} while (r != 0);
\treturn 0;
}
发表评论 取消回复