C++ 指针堆栈
#ifndef PRO1_STCKTP_H
#define PRO1_STCKTP_H
template <class Type>
class Stack {
private:
enum {SIZE = 10};
int stacksize;
Type * items;
int top;
public:
explicit Stack(int ss = SIZE);
Stack(const Stack& st);
~Stack(){delete [] items;};
bool isempty(){ return top == 0; }
bool isfull(){ return top == stacksize;}
bool push(const Type & item);
bool pop(Type & item);
Stack &operator=(const Stack & st);
};
template <class Type>
Stack<Type>::Stack(int ss) :stacksize(ss), top(0){ items = new Type[stacksize]; }
template <class Type>
Stack<Type>::Stack(const Stack &st) {
stacksize = st.stacksize;
top = st.top;
items = new Type[stacksize];
for(int i = 0; i < top; i++)
items[i] = st.items[i];
}
template <class Type>
bool Stack<Type>::push(const Type &item) {
if (top < stacksize) {
items[top++] = item;
return true;
} else
return false;
}
template <class Type>
bool Stack<Type>::pop(Type &item) {
if (top > 0) {
item = items[--top];
return true;
} else
return false;
}
template <class Type>
Stack<Type>& Stack<Type>::operator=(const Stack<Type> &st) {
if (this == &st) {
return *this;
}
delete [] items;
stacksize = st.stacksize;
top = st.top;
items = new Type[stacksize];
for (int i = 0; i < top; i++)
items[i] = st.items[i];
return *this;
}
#endif //PRO1_STCKTP_H
#include "stcktp.h"
#include <iostream>
#include "module11_class_template/pointer_stack/stcktp.h"
using namespace std;
// 正确使用指针堆栈
const int Num = 10;
void usePointerStack(){
srand(time(0));
cout << "Please enter stack size: ";
int stacksize;
cin >> stacksize;
Stack<const char *> st(stacksize);
const char * in[Num] = {
"1:Hank Gilgamesh", "2:Kiki Ishtar", "3:Betty Rocker", "4:Ian Flagranti",
"5:Wolfgang Kibble", "6:Portia Koop", "7:Joy Almonda", "8:Xaverie Paprika",
"9:Juan Moore", "10:Misha Mache"
};
const char * out[Num];
int processed = 0;
int nextin = 0;
while (processed < Num) {
if (st.isempty()) {
st.push(in[nextin++]);
} else if(st.isfull())
st.pop(out[processed++]);
else if (rand()%2 && nextin < Num)
st.push(in[nextin++]);
else
st.pop(out[processed++]);
for (int i = 0; i < Num; i++)
cout << out[i] << endl;
cout << "Bye\n";
}
}
int main() {
usePointerStack();
return 0;
}