3.
试编写一个栈的类模板(包括其成员函数定义),以便为任何类型的对象提供栈结构数据的操作。操作至少包括:入栈和出栈操作。
#include <iostream> #include<cassert> using namespace std; template <class T,int SIZE = 50>//类模板 class Stack { private: T list[SIZE];//数组大小是size int top;//准备定义一个栈顶的指针 public: Stack();//构造函数 void push(const T &item);//压入栈 T pop();//弹出栈 void clear();//清空栈 const T &peek() const;//读取栈顶的数据但是不删除 bool Empty() const;//判断栈是否为空 bool Full() const;//判断栈是否满 }; template<class T,int SIZE>//定义一个类模板的时候,每个成员函数在初始化的时候第都要写这个 Stack<T,SIZE>::Stack():top(-1){}//这个是将成员变量top指针设置成-1,有点想成员函数初始化形参的时候 template<class T,int SIZE> void Stack<T,SIZE>::push(const T &item) { assert(!Full());//不满的时候,才能压进去 list[++top] = item;//先将top指针加1,只想下一个可用的空间然后放进去 } template<class T,int SIZE> T Stack<T,SIZE>::pop() { assert(!Empty());//不满才能 return list[top--];//这个要先返回元素在-1 } template<class T,int SIZE> const T &Stack<T,SIZE>::peek() const { assert(!Empty()); return list[top]; //返回栈顶元素二栈顶的指针并不变 } template<class T,int SIZE> bool Stack<T,SIZE>::Empty() const { return top == -1; } template<class T,int SIZE> bool Stack<T,SIZE>::Full() const { return top == SIZE-1; } template<class T,int SIZE> void Stack<T,SIZE>::clear() { top = -1; } int main() { Stack <int> a; for(int i = 0;i<5;i++) { a.push(i); } cout << a.peek(); cout << endl; for(int i=0;i<5;i++) { int c; c = a.pop(); cout << c <<" "; } a.clear(); cout << endl; Stack <char> b; b.push('a'); b.push('b'); b.push('c'); b.push('d'); for(int i=0;i<4;i++) { int d; d = b.pop(); cout << d <<" "; } b.clear(); cout << endl; }