#include<iostream>
#include<exception>
using namespace std;
class OutOfRange:public exception {
public:
const char* what()const throw() {
return "ERROE! OUT OF Range.\n";
}
};
class BadSize:public exception {
public:
const char* what()const throw() {
return "ERROR! BAD SIZE.\n";
}
};
template<class T>
class Stack {
public:
virtual bool isEmpty()const = 0;
virtual bool isFull()const = 0;
virtual void clear() = 0;
virtual int size()const = 0;
virtual void push(const T& x) = 0;
virtual T pop() = 0;
virtual T getTop()const = 0;
virtual ~Stack() = 0;
};
template<class T>
class seqStack :public Stack<T> {
private:
T* data;
int maxSize;
int top;
void resize();
public:
seqStack(int initSize = 100);
~seqStack() { delete[] data; }
bool isEmpty()const { return top == -1; }
bool isFull()const { return top + 1 == maxSize; }
void clear() { top = -1; }
int size() { return top + 1; }
void push(const T& x);
T pop();
T getTop()const;
};
template<class T>
seqStack<T>::seqStack(int initSize) {
if (initSize <= 0) throw BadSize();
data = new T[initSize];
maxSize = initSize;
top = -1;
}
template<class T>
void seqStack<T>::push(const T& x) {
if (isFull()) resize();
data[++pop] = x;
}
template<class T>
T seqStack<T>::pop() {
if (isEmpty()) throw OutOfRange();
return data[top--];
}
template<class T>
T seqStack<T>::getTop()const {
if (isEmpty()) throw OutOfRange();
return data[top];
}
template<class T>
void seqStack<T>::resize() {
T* p = data;
data = new T[maxSize * 2];
for (int i = 0; i < maxSize; ++i) {
data[i] = p[i];
}
maxSize *= 2;
delete[] p;
}
template<class T>
class linkStack:public Stack<T> {
private:
struct LinkNode {
T val;
LinkNode* next;
LinkNode(LinkNode* p = nullptr, const T& x) : val(x), next(p) {}
}
LinkNode* top;
public:
linkStack():top(nullptr) {}
~linkStack() { clear(); }
void clear();
int size()const;
bool isEmpty()const { return top == nullptr; }
void push(const T& x);
T pop();
T getTop()const;
};
template<class T>
void linkStack<T>::clear() {
LinkNode* del = nullptr;
while(top) {
del = top;
top = top->next;
delete del;
}
}
template<class T>
int linkStack<T>::size()const {
LinkNode* p = top;
int cnt = 0;
while (p) {
p = p->next;
++cnt;
}
return cnt;
}
template<class T>
void linkStack<T>::push(const T& x) {
linkNode* p = new LinkNode(top, x);
top = p;
}
template<class T>
T linkStack<T>::pop() {
if (isEmpty()) throw OutOfRange();
T value = top->val;
LinkNode* del = top;
top = top->next;
delete del;
return value;
}
template<class T>
T linkStack<T>::getTop()const {
if (isEmpty()) throw OutOfRange();
return top->val;
}
【数据结构】栈
最新推荐文章于 2024-03-01 17:09:03 发布