顺序栈类的构建
template <class T>
class Stack {
public:
Stack(int size) {
elements = new T[size];
MaxSize = size;
topp =0;
}
~Stack()
{
delete []elements;
}
void OverStack() {
T* NewArray=NULL;
int size = MaxSize;
if (topp >= 0.5 * size) {
NewArray = new T[2 * size], MaxSize *= 2;
for (int i = 0; i < topp; ++i)
NewArray[i] = elements[i];
delete[]elements;
elements = NewArray;
}
}
bool IsFull() {
if (topp == MaxSize + 1)
return 1;
return 0;
}
bool IsEmpty() {
if (topp == 0)
return 1;
return 0;
}
int size() {
return topp;
}
void pop() {
if(!IsEmpty())
--topp;
}
void push(T a) {
OverStack();
++topp;
elements[topp - 1] = a;
}
T top() {
if(!IsEmpty())
return elements[topp - 1];
}
void clear() {
topp = 0;
}
private:
T* elements;
int topp;
int MaxSize;
};
双栈共享栈空间
template <class T>
class Stack {
public:
Stack(int size) {
elements = new T[size];
MaxSize = size;
topp0 = -1;
topp1 = MaxSize;
}
~Stack()
{
delete[]elements;
}
bool IsFull() {
if (topp0+1 == topp1)
return 1;
return 0;
}
bool IsEmpty0() {
if (topp0 == -1)
return 1;
return 0;
}
bool IsEmpty1() {
if (topp1 == MaxSize)
return 1;
return 0;
}
int size() {
return MaxSize;
}
void pop(int choice) {
if (choice != 1 && choice != 0)
return;
if (choice == 0 && !IsEmpty0()) {
--topp0; return;
}
if (choice == 1 && !IsEmpty1()) {
++topp1; return;
}
cout << "栈为空!" << endl;
return;
}
void push(T a, int choice) {
if ((choice != 1 && choice != 0) || topp0+1 == topp1)
return;
if (choice == 0) {
++topp0;
elements[topp0] = a;
}
else {
--topp1;
elements[topp1] = a;
}
}
T top(int choice) {
if (choice != 1 && choice != 0) {
cout << "输入的栈序号错误!" << endl;
return -1;
}
if (choice == 0&& !IsEmpty0()) {
return elements[topp0];
}
if(choice == 1 && !IsEmpty1()) {
return elements[topp1] ;
}
cout << "栈为空!" << endl;
return -1;
}
void clear() {
topp0 = -1;
topp1 = MaxSize;
}
private:
T* elements;
int topp0,topp1;
int MaxSize;
};