使用一个队列实现栈的基本功能:push、pop、判断栈是否为空等,实现的代码如下:
#include<iostream>
#include<queue>
#include<ctime>//计算代码所需要的时间
using namespace std;
class MyStack
{
public:
queue<int> que;
//判断栈是否为空
bool empty()
{
return que.empty();
}
//入栈
void push(int x)
{
que.push(x);
}
//出栈
int pop()
{
int size = que.size();
size--;
while (size--)
{
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
//得到栈顶元素
int top()
{
return que.back();
}
};
int main()
{
clock_t starttime, endtime;
starttime = clock();//计时开始
MyStack mystack;
for (int i = 1; i < 4; i++)
{
mystack.push(i);
}
cout << "栈顶元素为:" << mystack.top() << endl;
endtime = clock();//计时开始
cout << "运行时间为: " << (double)(endtime - starttime) / CLOCKS_PER_SEC << "s" << endl;
system("pause");
return 0;
}