65,210
社区成员
发帖
与我相关
我的任务
分享
#ifndef STACKTP1_H_
#define STACKTP1_H_
template<class Type>
class Stack
{
private:
static const int 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>
inline 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;
}
return false;
}
template<class Type>
bool Stack<Type>::pop(Type& item)
{
if (top > 0)
{
item = items[--top];
return true;
}
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 // !STACKTP1_H_
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "stacktp1.h"
using std::cin;
using std::cout;
using std::endl;
using std::string;
const int Num = 10;
int main()
{
srand(time(0));
cout << "Please enter stack size: ";
int stacksize;
cin >> stacksize;
Stack<char*>st(stacksize);
const char* in[Num] = {
" 1: Hank Gilgamesh"," 2: Kiki Ishtar",
" 3: Betty Rocker"," 4: Ian Flagrant",
" 5: Wolfgang Kibble"," 6 Portia Koop",
" 7: Joy Almondo"," 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";
return 0;
}