用c++利用顺序存储结构和链式存储结构,设计算法并编写程序实现顺序栈和链栈的定义,创建,入栈和出栈
时间: 2024-12-16 21:14:53 浏览: 8
在C++中,我们可以分别使用数组(顺序存储)和动态内存(链式存储)来实现栈的数据结构。
**顺序栈(基于数组)**:
```cpp
#include <iostream>
using namespace std;
const int MAX_SIZE = 100; // 栈的最大容量
class SequentialStack {
private:
int top;
int data[MAX_SIZE];
public:
SequentialStack() : top(-1) {}
bool isEmpty() const { return top == -1; }
bool isFull() const { return top == MAX_SIZE - 1; }
void push(int value) {
if (isFull()) {
cout << "Stack overflow!" << endl;
return;
}
top++;
data[top] = value;
}
int pop() {
if (isEmpty()) {
cout << "Stack underflow!" << endl;
return -1;
}
int poppedValue = data[top];
top--;
return poppedValue;
}
// 其他辅助函数...
};
// 使用示例
int main() {
SequentialStack seqStack;
seqStack.push(5);
seqStack.push(10);
cout << "Top element: " << seqStack.pop() << endl;
return 0;
}
```
**链式栈(基于链表)**:
```cpp
#include <iostream>
struct Node {
int value;
Node* next;
Node(int val = 0) : value(val), next(nullptr) {}
};
class LinkedStack {
private:
Node* top;
public:
LinkedStack() : top(nullptr) {}
bool isEmpty() const { return top == nullptr; }
void push(int value) {
Node* newNode = new Node(value);
newNode->next = top;
top = newNode;
}
int pop() {
if (isEmpty()) {
cout << "Stack underflow!" << endl;
return -1;
}
Node* poppedNode = top;
top = top->next;
delete poppedNode;
return poppedNode->value;
}
// 其他辅助函数...
};
int main() {
LinkedStack linkStack;
linkStack.push(5);
linkStack.push(10);
cout << "Top element: " << linkStack.pop() << endl;
return 0;
}
```
阅读全文