栈实现进制的转换(c语言)
#include<stdio.h> #include<malloc.h> #define SIZE 100 //栈的最大长度 #define STEPTSIZE 10 //栈每次增长的长度 typedef int ElemType; /*栈的定义*/ typedef struct stack{ ElemType *base; ElemType *top; int stackSize; }stack; /*栈顶初始化*/ void initAStack(stack *s){ s->base =(ElemType *)malloc(SIZE*sizeof(ElemType)); if(s->base == NULL) exit(0); s->top = s->base; s->stackSize = SIZE; } /*进栈*/ void push(stack *s,ElemType e){ /*栈满*/ if( (s->top - s->base) == SIZE){ s->base = (ElemType *)realloc(s->base,(SIZE+STEPTSIZE)*sizeof(ElemType)); s->stackSize += STEPTSIZE; } *(s->top) =e; s->top++; } /*遍历*/ void traverseStack(stack s){ while(s.top != s.base){ s.top--; printf("%d\t",*s.top); } printf("\n"); } /*出栈*/ void pop(stack *s){ if(s){ int *tem; tem = s->top; s->top--; free(tem); }else{ printf("null element"); } }
/*转换函数*/
void transform( stack s,int n){ int number = 0; printf("please input the number which want to be transfromed.\n"); scanf("%d",&number); while(number){ push(&s,number%8); number= number/n; } traverseStack(s); } void main(){ stack s; initAStack(&s); transform( s, 8); }
海纳百川,有容乃大