写一个c++程序首先分别实现顺序栈、链栈的各种基本运算;其次设计程序调用顺序栈、链栈的这些算法进行功能测试。
时间: 2024-11-24 09:43:03 浏览: 26
在C++中,我们可以先分别实现顺序栈(数组栈)和链栈(链表栈)的数据结构及基本操作。以下是简单的示例:
**顺序栈(数组栈)实现:**
```cpp
#include <iostream>
using namespace std;
#define MAX_SIZE 100
class ArrayStack {
private:
int top;
int data[MAX_SIZE];
public:
ArrayStack() : top(-1) {}
bool isEmpty() { return top == -1; }
void push(int value) {
if (top < MAX_SIZE - 1) {
top++;
data[top] = value;
} else {
cout << "Stack overflow.\n";
}
}
int pop() {
if (!isEmpty()) {
int value = data[top];
top--;
return value;
} else {
cout << "Stack underflow.\n";
return -1;
}
}
int peek() { return isEmpty() ? -1 : data[top]; }
};
```
**链栈(链表栈)实现:**
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
class LinkedStack {
private:
Node* top;
public:
LinkedStack() : top(nullptr) {}
bool isEmpty() { return top == nullptr; }
void push(int value) {
Node* newNode = new Node{value, top};
top = newNode;
}
int pop() {
if (!isEmpty()) {
Node* temp = top;
top = top->next;
delete temp;
return temp->data;
} else {
cout << "Stack underflow.\n";
return -1;
}
}
int peek() { return isEmpty() ? -1 : top->data; }
};
```
接下来,我们编写主函数来测试这两种栈的特性:
```cpp
int main() {
ArrayStack arrStack;
LinkedStack lnkStack;
// 测试顺序栈
arrStack.push(1);
arrStack.push(2);
cout << "Peek from array stack: " << arrStack.peek() << endl;
cout << "Pop from array stack: " << arrStack.pop() << endl;
// 测试链栈
lnkStack.push(3);
lnkStack.push(4);
cout << "Peek from linked stack: " << lnkStack.peek() << endl;
cout << "Pop from linked stack: " << lnkStack.pop() << endl;
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)