//pointor_stack.h
#ifndef POINTER_STACK_H_
#define POINTER_STACK_H_
#include<iostream>
template<typename Type>
class stack
{
private:
enum{size=8};
int stacksize;//栈分配的内存空间存放个数
Type *item;//需要构造深度复制构造函数和重载赋值运算符
int top;//栈内元素个数
public:
stack(int ss = 0);
stack(const stack &s);
~stack(){ delete[] item; }
bool isempty(){ return top == 0; }
bool isfull(){ return top == stacksize; }
bool push(const Type &i);
bool pop(Type &i);
stack& operator=(const stack &s);
};
/*对于模板类需要将定义和声明放在同一个文件中,因为在编译阶段并不为模板类分配内存*/
template<typename Type>
stack<Type>::stack(int ss) :stacksize(ss), top(0)
{
item = new Type[stacksize];
}
template<typename Type>
stack<Type>::stack(const stack &s)
{
stacksize = s.stacksize;
top = s.top;
item = new Type[stacksize];
for (int i = 0; i < top; i++)
item[i] = s.item[i];
}
template<typename Type>
bool stack<Type>::push(const Type &i)
{
if (isfull()) return false;
item[top++] = i;
return true;
}
template<typename Type>
bool stack<Type>::pop(Type &i)
{
if (isempty()) return false;
else
{
i = item[--top];//注意这里一定要是item[--top],因为item[top--]==item[top]不存在
return true;
}
}
template<typename Type>
stack<Type>& stack<Type>::operator=(const stack &s)//不要忘记stack<Type>
{
if (this == &s) return *this;
else
{
stacksize = s.stacksize;
top = s.top;
delete[] item;
item = new Type[stacksize];
for (int i = 0; i < top; i++)
item[i] = s.item[i];
return *this;
}
}
#endif //POINTER_STACK_H_
//main.cpp
/**
*Copyright U+00A9 2018 XXXX. All Right Reserved.
*Filename:
*Author:XXXXX
*Date:2018.12.01
*Version:VS 2013
*Description:
**/
#include<iostream>
#include<cstdlib>
#include<ctime>
#include"windows.h"
#include"pointer_stack.h"
using namespace std;
const int N = 6;
int main()
{
srand(time(0));
cout << "please input the size of stack: ";
int stacksize;
cin >> stacksize;
stack<const char *>st(stacksize);//创建指针栈
const char *in[N] = { " 1.Jack", " 2:Tom", " 3.Jerry",
" 4.Edison", " 5.X-man", " 6.Chinese" };
const char *out[N];
int process = 0;
int innext = 0;
while (process < N)
{
if (st.isempty())
st.push(in[innext++]);
else if (st.isfull())
st.pop(out[process++]);
else if (rand()%2&&innext<N)
st.push(in[innext++]);
else
st.pop(out[process++]);
}
cout << "Result:\n";
for (int i = 0; i < N; i++)
cout << out[i] << endl;
cout << "Done!\n";
system("pause");
return 0;
}
程序运行结果