簡單使用棧實現隊列

#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;
}


發佈了28 篇原創文章 · 獲贊 5 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章