- 整理思维导图
- 使用模板类,实现顺序栈
- 写一个char类型的字符数组,对该数组访问越界时抛出异常,并做处理。
#include <iostream>
using namespace std;
template <typename T>
class Stack {
private:
T *data;
int capacity;
int topIndex;
public:
Stack(int capacity) {
this->capacity = capacity;
data = new T[capacity];
topIndex = -1;
}
~Stack() {
delete[] data;
}
bool isEmpty() const {
return topIndex == -1;
}
bool isFull() const {
return topIndex == capacity - 1;
}
void push(const T& element) {
if (isFull()) {
cout << "栈满\n";
return;
}
data[++topIndex] = element;
}
T pop() {
if (isEmpty()) {
cout << "栈空\n";
return T();
}
return data[topIndex--];
}
T top() const {
if (isEmpty()) {
cout << "栈空\n";
return T();
}
return data[topIndex];
}
};
int main() {
Stack<int> intStack(5);
intStack.push(10);
intStack.push(20);
intStack.push(30);
intStack.push(10);
intStack.push(20);
intStack.push(30);
cout << "栈顶元素: " << intStack.pop() << endl;
cout << "栈顶元素: " << intStack.pop() << endl;
cout << "栈顶元素: " << intStack.top() << endl;
return 0;
}