面试题:使用两个栈实现一个队列
栈和队列都是我们经常使用的数据结构, 栈 -> 后进先出, 队列 -> 先进先出 何其相似, 既然如此, 我们可不可以 试着 用 两个栈来试试实现一个队列呢
基本思想:我们使用两个栈, s1:实现入队,s2:实现出队 首先,将数据存放在栈s1中,然后将数据push进s2中,再将s2中的数据pop 出队列: (1)如果栈B不为空,直接弹出栈B的数据 (2)如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据
#include <iostream>
#include <stack>
#include <windows.h>
using namespace std;
template <typename T>
class MyQueue
{
public:
MyQueue( )
{}
~MyQueue( )
{}
void Push( const T& data )
{
s1.push( data );
++size;
}
void Pop( )
{
if ( true == Empty( ) )
throw new exception( "队列为空!\n" );
//我们不采用 将 s1 的元素全部压入 s2 后 再 对s2 进行 一次 pop 的做法。 如下的做法可以 节省一次 入栈的开销
if ( true == s2.empty( ) )
{
while( 1 != s1.size( ) )
{
s2.push( s1.top( ) );
s1.pop( );
}
s1.pop( );
}
else
{
s2.pop( );
}
--size;
}
bool Empty( )
{
if ( true == s1.empty( ) )
if ( true == s2.empty( ) )
return true;
return false;
}
size_t Size( )
{
return size;
}
T& Front( )
{
if ( true == Empty( ) )
throw new exception( "队列为空!\n" );
if ( true == s2.empty( ) )
{
while ( 0 != s1.size( ) )
{
s2.push( s1.top( ) );
s1.pop( );
}
}
return s2.top( );
}
T& Back( )
{
if ( true == Empty( ) )
throw new exception( "队列为空!\n" );
if ( true == s1.empty( ) )
{
while ( 0 != s2.size( ) )
{
s1.push( s2.top( ) );
s2.pop( );
}
}
return s1.top( );
}
private:
stack<T> s1; //注意,不要写成 stack s1; -> stack<T> s1. s1里面存的数据是 T 类型.
stack<T> s2;
size_t size;
};
void Test( )
{
MyQueue<int> q;
cout << q.Empty( ) << endl;
q.Push( 1 );
cout << q.Front( ) << endl;
cout << q.Back( ) << endl;
cout << q.Empty( ) << endl;
q.Push( 2 );
q.Push( 3 );
q.Push( 4 );
q.Push( 5 );
cout << q.Front( ) << endl;
cout << q.Back( ) << endl;
q.Pop( );
cout << q.Front( ) << endl;
cout << q.Back( ) << endl;
q.Pop( );
q.Pop( );
q.Pop( );
cout << q.Front( ) << endl;
cout << q.Back( ) << endl;
q.Pop( );
cout << q.Empty( ) << endl;
}
int main( )
{
Test( );
system( "pause" );
return 0;
}