您的位置:首页 > 职场人生

利用两个队列实现栈---进栈和出栈

2017-05-09 15:19 537 查看
根据两个队列实现一个栈,    大致思路与我上篇博客 ---> 根据两个栈实现一个队列  类似

所以直接贴出代码:

//两个队列实现一个栈, 思路 与 两个栈实现一个队列基本类似(我发过博客)

#include <queue>
#include <windows.h>
using namespace std;

template <typename T>
class MyStack
{
public:
MyStack( )
{}

~MyStack( )
{}

void Push( const T& data ) //除了构造析构, 这些函数你别忘了返回值哈.
{
q1.push( data );
}

void Pop( )
{
if ( true == Empty( ) )
throw new exception( "栈为空!\n" );

if ( false == q1.empty( ) ) //false!!! Not flase!
{
while ( 1 != q1.size( ) )
{
q2.push( q1.front( ) );

q1.pop( );
}

q1.pop( );
}
else
{
while ( 1 != q2.size( ) )
{
q1.push( q2.front( ) );

q2.pop( );
}

q2.pop( );
}
}

bool Empty( )
{
if ( true == q1.empty( ) )
if ( true == q2.empty( ) )
return true;

return false;
}

private:
queue<T> q1;
queue<T> q2;
};

void TestMyStack( )
{
MyStack<int> s;

s.Push( 1 );
s.Push( 2 );
s.Push( 3 );
s.Push( 4 );

s.Pop( );

s.Push( 5 );
s.Push( 6 );

s.Pop( );
s.Pop( );
s.Pop( );
s.Pop( );
s.Pop( );
}

int main( )
{
TestMyStack( );

system( "pause" );
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息