两个栈实现一个队列

//aaa.hpp
#include <iostream>
using namespace std;
template<class T>
class Stack
{
public:
Stack()
:_array(NULL)
,_TopIndex(-1)
,_capacity(0)
{}
void Push(T x)
{
if(_TopIndex + 1 == _capacity)
{
_capacity = 2 * _capacity + 3;
int* temp = new T[_capacity];
memcpy(temp,_array,sizeof(int) * (_TopIndex + 1) );
delete []_array;
_array = temp;
}
_array[_TopIndex + 1] = x;
_TopIndex++;
}
void Pop()
{
_TopIndex--;
}
int Top()
{
if(_TopIndex > -1)
return _array[_TopIndex];
}
bool Empty()
{
return _TopIndex == -1;
}
public:
T* _array;
T _TopIndex;
T _capacity;
};

这个是.cpp文件
#include"aaa.hpp"
//void Test1()
//{
// Stack<int> s;
// s.Push(1);
// s.Push(2);
// s.Push(3);
// s.Push(4);
// while(!s.Empty())
// {
// int front = s.Top();
// cout<<front<<" ";
// s.Pop();
// }
//}
//实现队列
template<class T>
class Queue
{
public:
Queue()
{}
~Queue()
{}
void Push(T x)
{
while(!s2.Empty())
{
s1.Push(s2.Top());
s2.Pop();
}
s1.Push(x);
}
void Pop()
{
while(!s1.Empty())
{
s2.Push(s1.Top());
s1.Pop();
}
s2.Pop();
}
bool Empty()
{
return (s1.Empty() && s2.Empty());
}
const T Front()
{
while(!s1.Empty())
{
s2.Push(s1.Top());
s1.Pop();
}
int temp = s2.Top();
return temp;
}
private:
Stack<T> s1;
Stack<T> s2;
};
int main()
{
// Test1();
Queue<int> q1;
q1.Push(1);
q1.Push(2);
q1.Push(3);
q1.Push(4);
q1.Pop();
q1.Push(5);
while(!q1.Empty())
{
int front = q1.Front();
cout<<front<<" ";
q1.Pop();
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值