Python和C语言利用栈分别实现进制转换

Python和C语言利用栈分别实现进制转换

C语言实现

 

顺序表的存储结构实现栈

 

代码:

#include <stdlib.h>
#include <stdio.h>
 
#define STACK_INIT_SIZE 100   //栈初始开辟空间大小
#define STACK_INCREMENT 10    //栈追加空间大小
 
//栈的结构体
typedef struct stack{
    int *base;
    int *top;
    int size;
}binStack;
 
//栈初始化
binStack stack_init()
{
    binStack bs;
    bs.base = (int *)malloc(sizeof(int)*STACK_INIT_SIZE);
    bs.top = bs.base;
    bs.size = STACK_INIT_SIZE;
    return bs;
}
 
//入栈
void push(binStack *bs, int e)
{
    if(bs->top - bs->base >= bs->size)
    {
        bs->size += STACK_INCREMENT;
        bs->base = realloc(bs->base, bs->size);
    }
    *(bs->top++) = e;
}
 
//出栈
int pop(binStack *bs)
{
    if(bs->top != bs->base)
    {
        bs->top--;
        return *bs->top;
    }
    return -1;
}
 
//主函数
void main()
{
    int dec;
    binStack bs = stack_init();
    printf("请输入十进制整数:
");
    scanf("%d", &dec);
    while(dec)
    {
        push(&bs, dec%2);
        dec /= 2;
    }
    printf("转换后的二进制数是:
");
    while(bs.top != bs.base)
    {
        printf("%d", pop(&bs));
    }
    printf("

");
    system("date /T");
    system("TIME /T");
    system("pause");
    exit(0);    
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » Python和C语言利用栈分别实现进制转换