weixin_36652772 2016-11-08 12:37 采纳率: 0%
浏览 866

关于栈和用两个栈实现队列的算法程序的错误

#include
#include
using namespace std;

template
class CStack
{
public:
CStack(int arg) : elements(arg, 0){
size = arg;
topIndex = -1;
}

~CStack() {
}

void Push(T arg) {
    if (topIndex == size - 1)
        throw "Overflow";
    else
    {
        topIndex++;
        elements[topIndex]=arg;
    }
}

T Pop() {
    if (topIndex == -1)
        throw "Underflow";
    else
    {
        topIndex--;
        return elements[++topIndex];   
    }
}

bool IsEmpty() {
    if(topIndex==-1)
        return 1;
    else
        return 0;
}

private:
int size;
int topIndex;
vector elements;
};

template
class CQueueOnStack {
private:
CStack inbox;
CStack outbox;

public:
CQueueOnStack(int arg) : inbox(arg), outbox(arg) {}

void Enqueue (T arg1) {
       inbox.Push(arg1);
}

T Dequeue () {
    if(outbox.IsEmpty())
    {
        outbox.Push(inbox.Pop());
        return outbox.Pop();
    }
    else
        return outbox.Pop();
}

};

void testCStack() {
CStack stack(3);
try {
stack.Pop();
} catch (const char* e) {
printf("Catch %s exception\n", e);
}
stack.Push(1);
stack.Push(2);
stack.Push(3);

try {
    stack.Push(4);
} catch (const char* e) {
    printf("Catch %s exception\n", e);
}
while (!stack.IsEmpty())
    printf("%d\n", stack.Pop());

}

void testQueueOnStack() {
CQueueOnStack queue(10);
for (int i = 0; i < 5; ++i)
queue.Enqueue(i);
for (i = 0; i < 3; ++i)
printf("%d\n", queue.Dequeue());
queue.Enqueue(5);
queue.Enqueue(6);
for (i = 0; i < 4; ++i)
printf("%d\n", queue.Dequeue());
}

int main() {
testCStack();
testQueueOnStack();
return 0;
}
程序无法正确运行,不知道哪里有问题。

  • 写回答

1条回答 默认 最新

  • zqbnqsdsmd 2016-11-08 16:16
    关注
    评论

报告相同问题?

悬赏问题

  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别