思维导图使用模板类,实现顺序栈
#include <iostream>
using namespace std;
template<typename T>
class SeqStack {
private:
T* data;
int top;
int maxSize;
public:
SeqStack(int size = 10) {
maxSize = size;
data = new T[maxSize];
top = -1;
}
~SeqStack() {
delete[] data;
}
bool isEmpty() {
return top == -1;
}
bool isFull() {
return top == maxSize - 1;
}
void push(T x) {
if (isFull()) {
cout << "栈已满,无法入栈!" << endl;
return;
}
data[++top] = x;
}
T pop() {
if (isEmpty()) {
cout << "栈已空,无法出栈!" << endl;
return T();
}
return data[top--];
}
T topValue() {
if (isEmpty()) {
cout << "栈已空!" << endl;
return T();
}
return data[top];
}
};
int main() {
SeqStack stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
cout << "栈顶元素:" << stack.topValue() << endl;
cout << "出栈元素:" << stack.pop() << endl;
cout << "栈顶元素:" << stack.topValue() << endl;
return 0;
}