试使用链栈写一个C语言算法实现将用户输入的十进制数转二进制,及十进制转八进制,(请使用键盘录入用户输入的数据)
时间: 2024-05-04 17:17:13 浏览: 72
C语言实现十六进制数据转十进制数据
以下是使用链栈实现将用户输入的十进制数转二进制的C语言算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct StackNode {
int data;
struct StackNode *next;
} StackNode, *LinkStackPtr;
typedef struct {
LinkStackPtr top;
int count;
} LinkStack;
void InitStack(LinkStack *S) {
S->top = NULL;
S->count = 0;
}
int StackEmpty(LinkStack *S) {
return S->top == NULL;
}
int Push(LinkStack *S, int e) {
LinkStackPtr p = (LinkStackPtr) malloc(sizeof(StackNode));
if (!p) {
return 0;
}
p->data = e;
p->next = S->top;
S->top = p;
S->count++;
return 1;
}
int Pop(LinkStack *S, int *e) {
if (StackEmpty(S)) {
return 0;
}
LinkStackPtr p = S->top;
*e = p->data;
S->top = p->next;
free(p);
S->count--;
return 1;
}
int main() {
int n;
printf("请输入一个十进制数:");
scanf("%d", &n);
LinkStack S;
InitStack(&S);
while (n > 0) {
Push(&S, n % 2);
n /= 2;
}
printf("转换成二进制为:");
while (!StackEmpty(&S)) {
int e;
Pop(&S, &e);
printf("%d", e);
}
printf("\n");
return 0;
}
```
以下是使用链栈实现将用户输入的十进制数转八进制的C语言算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct StackNode {
int data;
struct StackNode *next;
} StackNode, *LinkStackPtr;
typedef struct {
LinkStackPtr top;
int count;
} LinkStack;
void InitStack(LinkStack *S) {
S->top = NULL;
S->count = 0;
}
int StackEmpty(LinkStack *S) {
return S->top == NULL;
}
int Push(LinkStack *S, int e) {
LinkStackPtr p = (LinkStackPtr) malloc(sizeof(StackNode));
if (!p) {
return 0;
}
p->data = e;
p->next = S->top;
S->top = p;
S->count++;
return 1;
}
int Pop(LinkStack *S, int *e) {
if (StackEmpty(S)) {
return 0;
}
LinkStackPtr p = S->top;
*e = p->data;
S->top = p->next;
free(p);
S->count--;
return 1;
}
int main() {
int n;
printf("请输入一个十进制数:");
scanf("%d", &n);
LinkStack S;
InitStack(&S);
while (n > 0) {
Push(&S, n % 8);
n /= 8;
}
printf("转换成八进制为:");
while (!StackEmpty(&S)) {
int e;
Pop(&S, &e);
printf("%d", e);
}
printf("\n");
return 0;
}
```
阅读全文