溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

編程開發(fā)中如何實現(xiàn)棧

發(fā)布時間:2021-10-21 11:27:55 來源:億速云 閱讀:113 作者:小新 欄目:編程語言

這篇文章主要介紹了編程開發(fā)中如何實現(xiàn)棧,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

/*****************************              WZ ASUST 2016
         
*****************************/
 #include <iostream>  
using namespace std;
const int StackSize=10;  
template <class T>        
class SeqStack
{
public:
    SeqStack( ) ;            //構(gòu)造函數(shù),棧的初始化
	~SeqStack( );            //析構(gòu)函數(shù)
    void Push(T x);          //將元素x入棧
    T Pop( );                //將棧頂元素彈出
    T GetTop( );	         //取棧頂元素(并不刪除)
	bool Empty( );           //判斷棧是否為空
private:
    T data[StackSize];      //存放棧元素的數(shù)組
    int top;                //棧頂指針,指示棧頂元素在數(shù)組中的下標
};
 
template <class T>
SeqStack<T>::SeqStack( )
{
	top=-1;
}
 
template <class T>
SeqStack<T>::~SeqStack( )
{
}
 
template <class T>
void SeqStack<T>::Push(T x)
{
    if (top== StackSize-1) throw "上溢";
    top++;
    data[top]=x;
}
 
template <class T>
T SeqStack<T>::Pop( )
{
    T x;
    if (top==-1) throw "下溢";
    x=data[top--];
    return x;
}
 
template <class T>
T SeqStack<T>::GetTop( )
{
	if (top!=-1)  
    return data[top];
}
 
template <class T>
bool SeqStack<T>::Empty( )
{
	if(top==-1) return 1;
	else return 0;
}
 
void test1()
{    
    SeqStack<int> a;      //創(chuàng)建模板類的實例
   
    if (a.Empty( )){
	
		cout<<"???執(zhí)行入棧操作:"<<endl;
    	cout<<"對15和10執(zhí)行入棧操作:"<<endl;
	    try
		{
			a.Push(15);
	        a.Push(10);  
		}
		catch(char* wrong)
		{
			cout<< wrong;
		}
		
		cout<<"棧頂元素為:"<<endl;   //取棧頂元素
		cout<<a.GetTop( )<<endl;
		    
	    cout<<"執(zhí)行出棧操作:"<<endl;
	    cout<<a.Pop( )<<endl;          //執(zhí)行出棧操作
        cout<<"棧頂元素為:"<<endl;
	    cout<<a.GetTop( )<<endl;	
	}
	else{
	
		cout<<"棧不空"<<endl;
	}
}
int main()
{
test1();
return 0;
}

感謝你能夠認真閱讀完這篇文章,希望小編分享的“編程開發(fā)中如何實現(xiàn)?!边@篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI