C实例---进制转换(栈实现)

来源:互联网 发布:s7200plc密码破解软件 编辑:程序博客网 时间:2024/05/16 10:49

代码:

#include <stdio.h>#include <string.h>#include <stdlib.h>#define     STACKSIZE       100typedef     int             ElemType;enum {a = 10, b,c,d,e,f};typedef struct stack{    ElemType *base;    ElemType *top;}SeqStack;void InitialStack(SeqStack *Stack){    if ((Stack->base = (ElemType *)malloc(STACKSIZE * sizeof(ElemType))) == NULL)    {        printf("Line %d : Stack malloc error!\n",__LINE__);        exit(1);    }    Stack->top = Stack->base;}int IsEmpty(SeqStack *Stack){    if (Stack->top== Stack->base)        return 1;    else        return 0;}int IsFull(SeqStack *Stack){    if ((Stack->top - Stack->base) == (STACKSIZE - 1))        return 1;    else        return 0;}void Push(SeqStack *Stack, ElemType data){    if (IsFull(Stack))    {        printf("Line %d : Stack Overflow!\n",__LINE__);        exit(2);    }    *(Stack->top ++) = data;}ElemType Pop(SeqStack *Stack){    if (IsEmpty(Stack))    {        printf("Line %d : Stack overflow!\n",__LINE__);        exit(3);    }    return *--Stack->top;}ElemType Top (SeqStack *Stack){    if (IsEmpty(Stack))    {        printf("Line %d : Stack overflow!\n",__LINE__);        exit(4);    }    return *(Stack->top -1);}void Conversion(SeqStack *Stack, int N, int B){    int i;    InitialStack(Stack);    while (N)    {        Push(Stack, N % B);        N = N / B;    }    while (!IsEmpty(Stack))    {        i = Pop(Stack);        printf("%d",i);    }    printf("\n");}int main(){    SeqStack *Stack;    printf("十进制 : 10\n");    printf("二进制 : ");    Conversion(Stack, 10, 2);    return 0;}

运行结果:
这里写图片描述

0 0
原创粉丝点击