未测试边界条件
MyStack.h
#ifndef __MYSTACK__
#define __MYSTACK__
#pragma once
//若出现链接错误无法解析的外部符号 "public: int __thiscall MyStack<int>::pop(void)" (?pop@?$MyStack@H@@QAEHXZ),该符号在函数 _main 中被引用
//请将MyStack.cpp的代码移入本h文件
#include <iostream>
#include <queue>
using namespace std;
template <class T>
class MyStack{
public:
MyStack(){};
~MyStack(){};
void push(const T& node);
T pop();
private:
queue<T> queue1;
queue<T> queue2;
};
#endif
MyStack.cpp
#include "MyStack.h"
template <class T>
void MyStack<T>::push(const T& node){
if (queue1.size() && queue2.size()){
cout <<"two queue must have a empty!\n";
return;
}
if (queue1.size()){
queue1.push(node);
}
else{
queue2.push(node);
}
}
template <class T>
T MyStack<T>::pop(){
if (queue1.size() && queue2.size()){
cout <<"two queue must have a empty!\n";
return NULL;
}
if (!queue1.size() && !queue2.size()){
cout <<"two queue must have a not empty!\n";
return NULL;
}
if (queue1.size()){
while(queue1.size() > 1){
T& node = queue1.front();
queue1.pop();
queue2.push(node);
}
T& node_pop = queue1.front();
queue1.pop();
return node_pop;
}
else{
while(queue2.size() > 1){
T& node = queue2.front();
queue2.pop();
queue1.push(node);
}
T& node_pop = queue2.front();
queue2.pop();
return node_pop;
}
}
main.cpp
#include <iostream>
#include "MyStack.h"
using namespace std;
int main(){
MyStack<int> st;
st.push(1);
st.push(2);
cout << st.pop() <<endl;
st.push(3);
cout << st.pop() <<endl;
cout << st.pop() <<endl;
int ttt = 1;
return 0;
}