简单使用栈实现队列

#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;
stack<int> stack1;
stack<int> stack2;
void appendTail(int ele)
{
    stack1.push(ele);
}
int deleteHead()
{
    int head;
    if(stack2.size()<=0)
    {
        while(stack1.size()>0)
        {
            int data = stack1.top();
            stack1.pop();
            stack2.push(data);
        }
    }
    if(stack2.size()==0)//这里不知道怎么处理,就返回了一个负一,抛异常不知道为什么不好使
        return -1;
    head = stack2.top();
    stack2.pop();
    return head;
}

int main()
{
    appendTail(1);
    appendTail(2);
    appendTail(3);
    int head=deleteHead();
    cout<<head<<endl;
    head=deleteHead();
    cout<<head<<endl;
    appendTail(4);
    head=deleteHead();
    cout<<head<<endl;
    appendTail(5);
    head=deleteHead();
    cout<<head<<endl;
    head=deleteHead();
    cout<<head<<endl;
    return 0;
}


posted on 2014-06-22 12:11  XiaoFei Wang  阅读(119)  评论(0编辑  收藏  举报

导航