#include<stdio.h>
#include<string.h>
#define maxsize 100
typedef struct
{
int data[maxsize];
int top;
}stack;
void stackfull()
{
printf("FULL!\n");
}
void start(stack* s)
{
s->top=-1;
}
int push(stack* s,int t)
{
if(s->top!=maxsize-1)
{
++s->top;
s->data[s->top]=t;
}
else
stackfull();
return 0;
}
int pop(stack* s)
{
int x;
if(s->top!=-1)
{
x=s->data[s->top];
s->top--;
return x;
}
return -1;
}
void transform(int x,char* arr)
{
stack s;
int t;
start(&s);
while(x)
{
t=x%2;
x=(x-t)/2;
push(&s,t);
}
int i=0;
// while(s->top!=-1)
// {
// arr[i++]=(char)(pop(&s)+'0');
// s->top--;
// }这里中似乎不能用s->top;编译器显示“error: base operand of '->' has non-pointer type 'stack' s->top--;”不知道是什么原因?
while(1)
{
t=pop(&s);
if(t==-1)
break;
arr[i++]=t+'0';printf("*%c\n",arr[i-1]);
}
}
int main()
{
int x;
char arr[64];
while(1)
{
memset(arr,'\0',sizeof(arr));
printf("input a number:\n");
scanf("%d",&x);
transform(x,arr);
printf("%s\n",arr);
}
return 0;
}
栈模板:(需要一个数组,与链表不同,只要一个结点)
1.start函数:
初始化,是栈底的值为-1
2.push函数:
入栈,需要先判断栈是否满,栈满执行stackfull函数
3.pop函数:
出栈,需要先判断是否到达栈底,到栈底就结束