您的位置:首页 > 其它

两个栈实现双端队列

2014-09-21 22:47 204 查看
一个笔试题,当时竟然没想出来,现在实现下

/*
用两个栈实现双端队列
栈s1,s2。
pushback()和popback(),必须在s2为空的情况,把s2的都放s1中
pushfront()和popfront(),必须是在s1为空,把s1的都给放到s2中
*/
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
class DequeBy2Stack
{
private:
int maxsize;
stack<T> s1;
stack<T> s2;
public:
DequeBy2Stack(int size):maxsize(size){}
void pushback(T n);
T popback();
void pushfront(T n);
T popfront();
int size();
bool empty();
};
template <typename T>
bool DequeBy2Stack<T>::empty()
{
return s2.empty()&&s1.empty();
}
template <typename T>
int DequeBy2Stack<T>::size()
{
return s1.size()+s2.size();
}
template <typename T>
void DequeBy2Stack<T>::pushback(T n)
{
if(this->size()==maxsize)
{
throw new std::exception("Invalid push");
}
while(!s2.empty())           //必须将s2中的数据都导入到s1中
{
int tmp=s2.top();
s1.push(tmp);
s2.pop();
}
s1.push(n);
}
template <typename T>
T DequeBy2Stack<T>::popback()
{
while(!s2.empty())
{
int tmp=s2.top();
s1.push(tmp);
s2.pop();
}
if(!s1.empty())
{
int tmp=s1.top();
s1.pop();
return tmp;
}
else
{
throw new exception("Invalid popback()");
}
}
template <typename T>
void DequeBy2Stack<T>::pushfront(T n)
{
if(this->size()==maxsize)
{
throw new std::exception("Invalid push");
}
while(!s1.empty())
{
int tmp=s1.top();
s2.push(tmp);
s1.pop();
}
s2.push(n);
}
template <typename T>
T DequeBy2Stack<T>::popfront()
{
while(!s1.empty())
{
int tmp=s1.top();
s2.push(tmp);
s1.pop();
}
if(!s2.empty())
{
int tmp=s2.top();
s2.pop();
return tmp;
}
else
{
throw new exception("Invalid popfront");
}
}

int main()
{
DequeBy2Stack<int> test(8);
int n;
for(int i=1;i<=8;i++)
{
test.pushback(i);
}
test.popback();
test.popfront();
test.popfront();
test.popfront();
test.pushfront(100);
test.pushfront(101);
test.pushback(30);
test.pushfront(102);
test.popfront();
while(!test.empty())
cout<<test.popback()<<endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: