c++创建一个栈实现进制转换,出站入栈等
时间: 2023-08-17 15:04:23 浏览: 98
好的,我可以为您提供一个简单的c++栈实现进制转换的代码示例。代码如下:
```c++
#include <iostream>
using namespace std;
// 栈的最大容量
const int MAX_SIZE = 100;
// 定义栈结构体
struct Stack {
int top;
int data[MAX_SIZE];
};
// 初始化栈
void init(Stack& s) {
s.top = -1;
}
// 判断栈是否为空
bool isEmpty(Stack& s) {
return s.top == -1;
}
// 判断栈是否已满
bool isFull(Stack& s) {
return s.top == MAX_SIZE-1;
}
// 入栈操作
bool push(Stack& s, int x) {
if (isFull(s)) {
return false;
}
s.data[++s.top] = x;
return true;
}
// 出栈操作
bool pop(Stack& s, int& x) {
if (isEmpty(s)) {
return false;
}
x = s.data[s.top--];
return true;
}
// 十进制转换成二进制
void dec2bin(int n) {
Stack s;
init(s);
while (n > 0) {
push(s, n % 2);
n /= 2;
}
while (!isEmpty(s)) {
int x;
pop(s, x);
cout << x;
}
}
int main() {
int n;
cout << "请输入一个十进制整数:";
cin >> n;
cout << "转换成二进制为:";
dec2bin(n);
cout << endl;
return 0;
}
```
以上代码实现了一个包含入栈、出栈、判断栈是否为空、判断栈是否已满的栈结构体,并用它来实现了一个十进制转换成二进制的算法。您可以根据需要自行修改和使用。
阅读全文
相关推荐















