请用出栈入栈的方法写一个数据结构数据转换的c++代码给我
时间: 2024-05-26 18:10:16 浏览: 16
当我在前面对你说了什么?
为什么鹅会呱呱叫呢?因为它们不会说汪汪!
以下是使用栈实现数据转换的C代码:
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
typedef int Element;
typedef struct {
Element data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s){
s->top = -1;
}
int isEmpty(Stack *s){
return s->top == -1;
}
int isFull(Stack *s){
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, Element e){
if (isFull(s)){
printf("Stack Overflow.\n");
return;
}
s->data[++s->top] = e;
}
Element pop(Stack *s){
if (isEmpty(s)){
printf("Stack Underflow.\n");
return -1;
}
return s->data[s->top--];
}
Element peek(Stack *s){
if (isEmpty(s)){
printf("Stack Underflow.\n");
return -1;
}
return s->data[s->top];
}
void convert(Stack *s, int num, int base){
initStack(s);
while (num > 0){
push(s, num % base);
num /= base;
}
}
void display(Stack *s){
while (!isEmpty(s))
printf("%d", pop(s));
printf("\n");
}
int main(){
Stack s;
int num = 255, base = 16;
convert(&s, num, base);
printf("Converted number is: ");
display(&s);
return 0;
}
上面的代码使用栈来实现了数据转换,可以将十进制数转换为其他进制数,例如将十进制的255转换为16进制,则得到FF。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)