链栈的基本操作c++源代码
时间: 2024-09-15 16:13:18 浏览: 54
链栈是一种基于链表的数据结构,其基本操作主要包括入栈(push)、出栈(pop)、查看栈顶元素(top)以及判断栈是否为空(empty)。以下是C++中的链栈基础操作的简单实现:
```cpp
#include <iostream>
// 定义节点结构体
struct Node {
int data;
Node* next;
};
class Stack {
private:
Node* top; // 栈顶指针
public:
// 构造函数,初始化栈为空
Stack() : top(nullptr) {}
// 检查栈是否为空
bool isEmpty() const {
return top == nullptr;
}
// 入栈操作
void push(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = top;
top = newNode;
std::cout << "Pushed: " << value << std::endl;
}
// 出栈操作,返回并删除栈顶元素,若空则抛异常
int pop() {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
int poppedValue = top->data;
Node* temp = top;
top = top->next;
delete temp;
std::cout << "Popped: " << poppedValue << std::endl;
return poppedValue;
}
// 查看栈顶元素但不删除它
int peek() const {
if (isEmpty()) {
throw std::runtime_error("Stack is empty");
}
return top->data;
}
};
int main() {
Stack s;
s.push(1);
s.push(2);
s.push(3);
try {
std::cout << "Top element: " << s.peek() << std::endl;
s.pop(); // 输出:Popped: 3
std::cout << "After pop: Top element is " << s.peek() << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
```
阅读全文