十进制转换到二进制(用自定义的栈实现

#include <stdio.h>
#include "stack.h"

int main()
{
    stack st1;
    init_stack(&st1);
    int dec;
    int temp;
    
    printf("Input a integer, then it will be changed to binary:");
    while (scanf("%d", &dec) != 1)
    {
        printf("input error!\n");
        while (getchar() != '\n')
            continue;
        printf("Input a integer, then it will be changed to binary:");
    }
    
    temp = dec;
    while (temp != 0)
    {
        push_stack(&st1, temp%2);
        temp /= 2;
    }

    printf("%d's binary is :\n", dec);
    while (!empty_stack(&st1))
    {
        printf("%d ", pop_stack(&st1));
    }

    return 0;
}




//以下是头文件

#ifndef __STACK_H__
#define __STACK_H__

#define MAX 20
typedef int datatype;
typedef struct stack{
    datatype data[MAX];
    int top;
}stack, *pstack;

extern void init_stack(pstack);
extern int empty_stack(pstack);
extern int full_stack(pstack);
extern int clear_stack(pstack);
extern int push_stack(pstack, datatype value);
extern datatype pop_stack(pstack);
extern datatype get_top_data(pstack);
extern int num_stack(pstack);

#endif


//以下是实现

#include <stdio.h>
//#define NDEBUG
#include <assert.h>
#include "stack.h"

void init_stack(pstack sp)
{
    assert(NULL != sp);
    sp->top = -1;
    return ;
}

int empty_stack(pstack sp)
{
    assert(NULL != sp);
    return (-1 == sp->top);
}

int full_stack(pstack sp)
{
    assert(NULL != sp);
    return (MAX-1 == sp->top);
}

int clear_stack(pstack sp)
{
    assert(NULL != sp);
    return (sp->top = -1);
}

int push_stack(pstack sp, datatype value)
{
    assert(NULL != sp);
    if (full_stack(sp))
    {
        printf("stack is full!\n");
        return -1;
    }

    sp->data[++(sp->top)] = value;
    return 0;
}

datatype pop_stack(pstack sp)
{
    assert(NULL != sp);
    if (empty_stack(sp))
    {
        printf("stack is empty!\n");
        return -1;
    }
    return sp->data[(sp->top)--];
}

datatype get_top_data(pstack sp)
{
    assert(NULL != sp);
    if (empty_stack(sp))
    {
        printf("stack is empty!\n");
        return -1;
    }
    return sp->data[sp->top];
}

int num_stack(pstack sp)
{
    assert(NULL != sp);
    return (sp->top + 1);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值