您的位置:首页 > 理论基础 > 数据结构算法

【C++数据结构学习笔记---栈】用数组实现栈

2013-03-18 09:00 483 查看
【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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: