帮我用c++写一个顺序栈和链栈
时间: 2024-10-23 07:19:44 浏览: 19
当然可以。以下是使用C++分别实现顺序栈(基于数组)和链栈(基于链表)的基本结构:
**顺序栈(Array-based Stack)**
```cpp
#include <vector>
template<typename T>
class ArrayStack {
public:
// 初始化栈容量
ArrayStack(int capacity) : top_(0), capacity_(capacity) {}
// 判断栈是否为空
bool empty() const { return top_ == 0; }
// 判断栈是否已满
bool is_full() const { return top_ == capacity_; }
// 入栈操作
void push(const T& value) {
if (is_full()) {
throw std::overflow_error("Stack overflow");
}
data_.push_back(value);
top_++;
}
// 出栈操作
T pop() {
if (empty()) {
throw std::underflow_error("Stack underflow");
}
T value = data_[top_ - 1];
data_.pop_back();
top_--;
return value;
}
private:
int top_;
int capacity_;
std::vector<T> data_;
};
```
**链栈(Linked List-based Stack)**
```cpp
#include <iostream>
template<typename T>
struct Node {
T value;
Node* next;
};
template<typename T>
class LinkedStack {
public:
LinkedStack() : top(nullptr) {}
~LinkedStack() {
while (!empty()) {
Node* temp = top;
top = top->next;
delete temp;
}
}
// 添加元素到栈顶
void push(const T& value) {
Node* newNode = new Node{value, nullptr};
newNode->next = top;
top = newNode;
}
// 删除并返回栈顶元素
T pop() {
if (empty()) {
throw std::runtime_error("Stack underflow");
}
T value = top->value;
Node* temp = top;
top = top->next;
delete temp;
return value;
}
// 判断栈是否为空
bool empty() const { return top == nullptr; }
private:
Node<T>* top;
};
```
阅读全文