环境配置
codeblocks
windows10
项目结构
代码
SqStackClass.h
#ifndef _SQSTACKCLASS_H_
#define _SQSTACKCLASS_H_
#include <iostream>
template <typename T>
class SqStackClass
{
public:
static const int MAXSIZE;
SqStackClass(void);
~SqStackClass(void);
bool StackEmpty(void) const;
bool StackFull(void) const;
bool Push(const T &e);
bool Pop(T &e);
bool GetTop(T &e) const;
protected:
private:
T *data;
int top;
};
template <typename T>
const int SqStackClass<T>::MAXSIZE = 100;
template <typename T>
SqStackClass<T>::SqStackClass(void)
{
data = new T[MAXSIZE];
top = 0;
}
template <typename T>
SqStackClass<T>::~SqStackClass(void)
{
delete []data;
}
template <typename T>
bool SqStackClass<T>::StackEmpty(void) const
{
return (0 == top);
}
template <typename T>
bool SqStackClass<T>::StackFull(void) const
{
return (MAXSIZE == top);
}
template <typename T>
bool SqStackClass<T>::Push(const T &e)
{
if (StackFull())
{
return false;
}
data[top++] = e;
return true;
}
template <typename T>
bool SqStackClass<T>::Pop(T &e)
{
if (StackEmpty())
{
return false;
}
e = data[--top];
return true;
}
template <typename T>
bool SqStackClass<T>::GetTop(T &e) const
{
if (StackEmpty())
{
return false;
}
e = data[top - 1];
return true;
}
#endif // _SQSTACKCLASS_H_
main.cpp
#include <iostream>
#include "SqStackClass.h"
using namespace std;
int main(void)
{
SqStackClass<int> S1;
SqStackClass<int> S2;
const int n = 10;
int a[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int e;
for (int i = 0; i < n; ++i)
{
S1.Push(a[i]);
}
S1.GetTop(e);
cout << "S1.top = " << e << endl;
cout << "S1: " << endl;
while (!S1.StackEmpty())
{
S1.Pop(e);
cout << e << " ";
S2.Push(e);
}
cout << endl;
S2.GetTop(e);
cout << "S2.top = " << e << endl;
cout << "S2: " << endl;
while (!S2.StackEmpty())
{
S2.Pop(e);
cout << e << " ";
}
cout << endl;
system("PAUSE");
return 0;
}