【C++數據結構學習筆記---棧】用數組實現棧

【C++數據結構學習筆記---棧】用數組實現棧

一個簡單的實現例子,初始化26個英文字母。

#include <iostream>
using namespace std;
template <typename T>
class Stack{
	public:
		Stack(int max=100);							//構造函數
		~Stack() {delete[] stk;}					//析構函數
		bool empty()const {return stk_top==-1;}		//判斷棧是否爲空
		bool full()const {stk_top==max_top;}		//判斷是否棧滿
		bool size()const {return stk_top+1;}		//返回棧的長度
		T top()const;								//返回棧頂元素
		Stack<T>& push(const T& x);					//將元素x入棧
		Stack<T>& pop(T& x);						//將元素x出棧
	private:
		int stk_top;
		int max_top;
		T *stk;
};
template <typename T>
Stack<T>::Stack(int max)
{
	max_top=max-1;
	stk=new T[max];
	stk_top=-1;
}
template <typename T>
T Stack<T>::top()const
{
	if (!empty()) return stk[stk_top];
}

template <typename T>
Stack<T>& Stack<T>::push(const T& x)
{
	stk[++stk_top]=x;
	return *this;
}
template <typename T>
Stack<T>& Stack<T>::pop(T& x)
{
	x=stk[stk_top--];
	return *this;
}
int main()
{
	int s1,s2;
	s1='A';
	s2='Z';
	Stack<char> stack;
	for(int i=s2;i>=s1;--i){
		stack.push(i);
	}
	char x;
	while(!stack.empty()){
		stack.pop(x);
		cout <<x <<" ";
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章