顺序栈
头文件
#define MAX 20
enum status {
success, overflow, underflow
};
template <class T>
class stack {
public:
stack();
bool isEmpty()const;
bool isFull()const;
status getTop(T& x)const;
status push(const T x);
status pop();
private:
int count;
int data[MAX];
};
源文件
#include"stack.h"
template <class T>
stack<T>::stack()
{
count = 0;
}
template <class T>
bool stack<T>::isEmpty()const {
return count == 0;
}
template <class T>
bool stack<T>::isFull()const {
return count == MAX;
}
template <class T>
status stack<T>::getTop(T& x)const {
if (isEmpty()) return underflow;
x = data[count - 1];
return success;
}
template <class T>
status stack<T>::push(const T x) {
if (isFull()) return overflow;
data[count] = x;
count++;
return success;
}
template <class T>
status stack<T>::pop() {
if (isEmpty()) return underflow;
count--;
return success;
}
template <class T>
bool ReferenceError(status a) {
if (a == overflow) {
cout << "overflow!" << endl;
return false;
}
if (a == underflow) {
cout << "underflow!" << endl;
return false;
}
return true;
}
链栈
enum status {
success,failed
};
template<class T>
struct node {
T data;
node<T>* next;
};
template<class T>
class LinkedStack {
public:
LinkedStack();
~LinkedStack();
bool isEmpty();
status getTop(T& x);
status push(T x);
status pop();
private:
int count;
node<T>* top;
};
template<class T>
LinkedStack<T>::LinkedStack() {
top = nullptr;
count = 0;
}
template<class T>
LinkedStack<T>::~LinkedStack() {
while (!isEmpty()) pop();
}
template<class T>
bool LinkedStack<T>::isEmpty() {
if (count==0) return true;
else return false;
}
template<class T>
status LinkedStack<T>::getTop(T& x) {
if (isEmpty()) return failed;
else {
x = top->data;
return success;
}
}
template<class T>
status LinkedStack<T>::push(T x) {
node<T>* cur = new node<T>;
cur->data = x;
cur->next = top;
top = cur;
count++;
return success;
}
template<class T>
status LinkedStack<T>::pop() {
if (isEmpty()) {
exit(0);
return failed;
}
else {
node<T>* cur = new node<T>;
cur = top;
top = top->next;
delete cur;
count--;
return success;
}
}