本文作者:韩申权
作者博客:http://www.cnblogs.com/hsqdboke
转载请注明出处,侵权必究,保留最终解释权!
用数制的转换算法调试顺序栈的基本操作算法。编写主程序调用数制的转换conversion算法,再由conversion调用InitStack、StackEmpty、Push、Pop算法。用不同的数转换成不同的进制调试程序并对相应的输出作出分析;修改输入数据,预期输出并验证输出的结果,加深对Push和Pop算法的理解。
#include<stdio.h> #include<stdlib.h> #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 #define ERROR 0 #define OK 1 #define OVERFLOW -1 typedef int status; typedef int 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(OVERFLOW); S->top=S->base; S->stacksize=STACK_INIT_SIZE; return OK; } status StackEmpty(SqStack *S) { if(S->base==S->top) return OK; else return ERROR; } 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(OVERFLOW); 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; } void conversion(int n,int m) { SqStack S; SElemType e; InitStack(&S); printf("%d进制转换为%d进制为: ",n,m); while(n) { push(&S,n%m); n/=m; } while(!StackEmpty(&S)) { pop(&S,&e); printf("%d",e); } printf("\n"); } int main() { int n,m; while(scanf("%d%d",&n,&m)!=EOF) { conversion(n,m); } }