#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);
}