完成栈和队列的类型定义,栈和队列的初始化、压栈、弹栈、入队、出队和输出等基本操作,完成指定的栈和队列设计题目(将一组整数逆置),并完成测试与运行。
时间: 2023-06-15 10:08:07 浏览: 60
好的,以下是栈和队列的类型定义、基本操作的实现以及逆置整数的代码:
```cpp
#include <iostream>
using namespace std;
// 栈的定义
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
// 初始化栈
void initStack(Stack &s) {
s.top = -1;
}
// 判断栈是否为空
bool isStackEmpty(Stack s) {
return s.top == -1;
}
// 判断栈是否已满
bool isStackFull(Stack s) {
return s.top == MAXSIZE - 1;
}
// 元素入栈
bool push(Stack &s, int element) {
if (isStackFull(s)) {
return false;
}
s.top++;
s.data[s.top] = element;
return true;
}
// 元素出栈
bool pop(Stack &s, int &element) {
if (isStackEmpty(s)) {
return false;
}
element = s.data[s.top];
s.top--;
return true;
}
// 队列的定义
typedef struct {
int data[MAXSIZE];
int front, rear;
} Queue;
// 初始化队列
void initQueue(Queue &q) {
q.front = q.rear = 0;
}
// 判断队列是否为空
bool isQueueEmpty(Queue q) {
return q.front == q.rear;
}
// 判断队列是否已满
bool isQueueFull(Queue q) {
return (q.rear + 1) % MAXSIZE == q.front;
}
// 元素入队
bool enqueue(Queue &q, int element) {
if (isQueueFull(q)) {
return false;
}
q.data[q.rear] = element;
q.rear = (q.rear + 1) % MAXSIZE;
return true;
}
// 元素出队
bool dequeue(Queue &q, int &element) {
if (isQueueEmpty(q)) {
return false;
}
element = q.data[q.front];
q.front = (q.front + 1) % MAXSIZE;
return true;
}
// 将一组整数逆置
void reverseNumbers(int a[], int n) {
Stack s;
initStack(s);
for (int i = 0; i < n; i++) {
push(s, a[i]);
}
for (int i = 0; i < n; i++) {
pop(s, a[i]);
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(a[0]);
reverseNumbers(a, n);
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果:
```
5 4 3 2 1
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)