帮我用c++实现一个链式栈
时间: 2024-09-22 21:01:20 浏览: 35
链式栈(Linked Stack)是一种基于链表数据结构实现的栈,它支持常数时间复杂度的入栈(push)和出栈(pop)操作。下面是一个简单的单链表实现的C++链式栈示例:
```cpp
#include <iostream>
// 链式栈节点定义
struct Node {
int data;
Node* next;
};
// 初始化链式栈的头节点
Node* top = nullptr;
// 定义栈的基本操作
class LinkedStack {
public:
// 入栈操作
void push(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = top;
top = newNode;
std::cout << "Pushed " << value << " to the stack." << std::endl;
}
// 出栈操作
int pop() {
if (isEmpty()) {
std::cerr << "Stack is empty! Cannot pop." << std::endl;
return -1; // 返回一个错误值表示栈空
}
int value = top->data;
Node* temp = top;
top = top->next;
delete temp;
return value;
}
// 查看栈顶元素(不修改栈)
int peek() const {
if (isEmpty()) {
std::cerr << "Stack is empty! Cannot peek." << std::endl;
return -1; // 返回一个错误值表示栈空
}
return top->data;
}
// 检查栈是否为空
bool isEmpty() const {
return top == nullptr;
}
private:
// 禁止直接访问堆栈内部结构
LinkedStack(const LinkedStack&) = delete;
LinkedStack& operator=(const LinkedStack&) = delete;
};
int main() {
LinkedStack stack;
stack.push(10);
stack.push(20);
stack.push(30);
std::cout << "Top element: " << stack.peek() << std::endl;
std::cout << "Popped element: " << stack.pop() << std::endl;
return 0;
}
```
阅读全文