利用兩個棧實現隊列的--->基本操作

面試題:使用兩個棧實現一個隊列 

棧和隊列都是我們經常使用的數據結構, 棧 -> 後進先出,  隊列  ->  先進先出   何其相似, 既然如此, 我們可不可以  試着 用 兩個棧來試試實現一個隊列呢



基本思想:我們使用兩個棧, 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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章