参考:《图解数据结构》,胡昭民著
/* 模板类 实现栈 */
#include<iostream>
using namespace std;
template< class Type = int, int size = 5>
class Stack
{
private:
Type st[size];//数组作为栈的存储空间
int top;//栈顶数据顶端索引
public:
Stack()
{
top = -1;
}
void push(Type data);
Type pop();
};
template< class Type, int size >
void Stack< Type, size>::push(Type data)
{
st[++top] = data;
}
template< class Type, int size >
Type Stack< Type, size>::pop()
{
return st[top--];
}
int main()
{
Stack<> st_1;
//Stack<char*,4> st_2;
Stack<string> st_2;
st_1.push(1);
st_1.push(2);
st_1.push(3);
cout<<"stack_1 [1] = "<<st_1.pop()<<endl;
cout<<"stack_1 [2] = "<<st_1.pop()<<endl;
cout<<"stack_1 [3] = "<<st_1.pop()<<endl;
cout<<endl;
st_2.push("first");
st_2.push("second");
st_2.push("third");
cout<<"stack_2 [1] = "<<st_2.pop()<<endl;
cout<<"stack_2 [2] = "<<st_2.pop()<<endl;
cout<<"stack_2 [3] = "<<st_2.pop()<<endl;
cout<<endl;
system("pause");
return 0;
}
模板类 栈
最新推荐文章于 2023-01-02 10:38:31 发布