不可以使用stl容器,帮我写出完整代码包括主程序
时间: 2023-12-03 11:02:40 浏览: 26
好的,以下是一个简单的例子,演示如何使用数组来实现栈的基本操作:
```c++
#include <iostream>
using namespace std;
// 定义栈的大小
#define MAX_SIZE 100
class Stack {
private:
int top; // 栈顶指针
int data[MAX_SIZE]; // 栈的数组
public:
Stack() {
top = -1; // 初始化栈顶指针
}
// 判断栈是否为空
bool isEmpty() {
return top == -1;
}
// 判断栈是否已满
bool isFull() {
return top == MAX_SIZE - 1;
}
// 入栈
void push(int value) {
if (isFull()) {
cout << "Stack overflow!" << endl;
return;
}
data[++top] = value;
}
// 出栈
int pop() {
if (isEmpty()) {
cout << "Stack underflow!" << endl;
return -1;
}
return data[top--];
}
// 获取栈顶元素
int peek() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
return -1;
}
return data[top];
}
// 打印栈中的所有元素
void print() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
return;
}
cout << "Stack elements: ";
for (int i = 0; i <= top; i++) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
Stack s;
// 将元素 1、2、3 入栈
s.push(1);
s.push(2);
s.push(3);
// 输出栈顶元素
cout << "Top element: " << s.peek() << endl;
// 出栈
cout << "Pop element: " << s.pop() << endl;
// 打印栈中所有元素
s.print();
return 0;
}
```