已知一个双向堆栈stack[M](M自己定义),编写程序实现:从键盘输入一个数据,若输入的是奇数,则存入左栈;若输入的是偶数,则存入右栈,直到栈满为止。
时间: 2024-02-22 21:59:21 浏览: 40
好的,根据您的要求,我来给您编写一个C++程序实现这个功能:
```c++
#include <iostream>
using namespace std;
const int M = 10; // 栈的最大容量
class DualStack {
private:
int left[M];
int right[M];
int top1, top2;
public:
DualStack() {
top1 = -1;
top2 = M;
}
bool isFull() {
return top2 - top1 == 1;
}
bool isEmpty(int flag) {
if (flag == 1) {
return top1 == -1;
} else {
return top2 == M;
}
}
bool push(int data, int flag) {
if (isFull()) {
return false;
}
if (flag == 1) {
left[++top1] = data;
} else {
right[--top2] = data;
}
return true;
}
bool pop(int &data, int flag) {
if (isEmpty(flag)) {
return false;
}
if (flag == 1) {
data = left[top1--];
} else {
data = right[top2++];
}
return true;
}
};
int main() {
DualStack stack;
int data;
while (cin >> data) {
if (data % 2 == 1) {
if (stack.push(data, 1)) {
cout << "Push " << data << " into the left stack." << endl;
} else {
cout << "Left stack is full." << endl;
}
} else {
if (stack.push(data, 2)) {
cout << "Push " << data << " into the right stack." << endl;
} else {
cout << "Right stack is full." << endl;
}
}
if (stack.isFull()) {
cout << "The dual stack is full." << endl;
break;
}
}
cout << "Pop data from the left stack:" << endl;
while (!stack.isEmpty(1)) {
stack.pop(data, 1);
cout << data << " ";
}
cout << endl;
cout << "Pop data from the right stack:" << endl;
while (!stack.isEmpty(2)) {
stack.pop(data, 2);
cout << data << " ";
}
cout << endl;
return 0;
}
```
程序中,我们定义了一个`DualStack`类,其中包含两个数组`left`和`right`分别表示左栈和右栈,以及两个栈顶指针`top1`和`top2`分别表示左栈和右栈的栈顶位置。类中定义了`isFull()`和`isEmpty(flag)`方法用于判断栈是否已满或者是否为空,`push(data, flag)`和`pop(data, flag)`方法用于入栈和出栈操作。
在主函数中,我们不断从键盘输入数据,如果是奇数则存入左栈,如果是偶数则存入右栈,直到栈满为止。最后从左栈和右栈中分别出栈并输出栈中的元素。
希望可以解决您的问题,如有不明白的地方可以再问我哦~
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)