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

来源:互联网 发布:linux如何安装显卡驱动 编辑:程序博客网 时间:2024/05/19 09:12

【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;}
原创粉丝点击