栈的十六进制转换c语言
时间: 2024-04-12 15:22:30 浏览: 102
以下是一个栈的十六进制转换C语言的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef char SElemType;
typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
} SqStack;
Status InitStack(SqStack *S) {
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S->base) {
exit(ERROR);
}
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack *S, SElemType e) {
if (S->top - S->base >= S->stacksize) {
S->base = (SElemType *)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof(SElemType));
if (!S->base) {
exit(ERROR);
}
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top++) = e;
return OK;
}
Status Pop(SqStack *S, SElemType *e) {
if (S->top == S->base) {
return ERROR;
}
*e = *(--S->top);
return OK;
}
int StackLen(SqStack S) {
return S.top - S.base;
}
int main() {
SqStack S;
int n;
SElemType c;
InitStack(&S);
printf("请输入一个十进制数:");
scanf("%d", &n);
while (n) {
Push(&S, n % 16);
n /= 16;
}
printf("转换为十六进制数为:");
while (StackLen(S)) {
Pop(&S, &c);
if (c < 10) {
printf("%d", c);
} else {
printf("%c", c - 10 + 'A');
}
}
printf("\n");
return 0;
}
```
阅读全文