用c++创建一个顺序栈实现并出栈和入栈的操作
时间: 2024-10-20 09:14:20 浏览: 81
在C++中,我们可以使用数组来简单地实现一个基本的顺序栈(也称为线性栈)。以下是创建栈、入栈(push)和出栈(pop)操作的基本步骤:
```cpp
#include <iostream>
// 定义栈的最大容量
const size_t MAX_SIZE = 10;
// 定义栈结构体
struct StackElement {
int value;
bool isOccupied; // 标记元素是否已入栈
};
// 序列化栈类
class SequentialStack {
private:
StackElement stack[MAX_SIZE];
size_t top; // 栈顶指针
public:
// 初始化栈为空
SequentialStack() : top(0) {}
// 判断栈是否为空
bool isEmpty() const { return top == 0; }
// 检查栈是否已满
bool isFull() const { return top == MAX_SIZE; }
// 入栈操作 (push)
void push(int value) {
if (!isFull()) {
stack[top].value = value;
stack[top].isOccupied = true;
top++;
} else {
std::cout << "Stack is full, cannot push." << std::endl;
}
}
// 出栈操作 (pop)
void pop() {
if (!isEmpty()) {
stack[top - 1].isOccupied = false; // 更新栈顶元素标记
top--;
} else {
std::cout << "Stack is empty, cannot pop." << std::endl;
}
}
// 查看栈顶元素(不弹出)
int peek() const {
if (!isEmpty()) {
return stack[top - 1].value;
} else {
std::cout << "Stack is empty." << std::endl;
return -1; // 返回默认值,表示空栈
}
}
};
int main() {
SequentialStack s;
s.push(5);
s.push(10);
std::cout << "Top element: " << s.peek() << std::endl;
s.pop();
std::cout << "After pop: Top element " << s.peek() << std::endl;
return 0;
}
阅读全文