题目:
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Stack
{
int* data;
int top;//栈顶
int capacity;//栈的容量
}ST;
void SLInit(ST* ps)
{
ps->data = NULL;
ps->capacity = 0;
ps->top = 0;//ps->top=-1
//初始化时top给0,意味着top指向栈顶数据的下一个
//初始化时top给1,意味着top指向栈顶数据
}
void StackPush(ST* ps, int x)
{
if (ps->top == ps->capacity)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//运用三目操作符,如果capacity=0,则给4个空间
int* tmp = (int*)realloc(ps->data, sizeof(int) * newCapacity);//realloc开辟空间
if (tmp == NULL)
{
exit(-1);
}//扩容失败则退出程序
ps->data = tmp;//内存开辟成功,将指针指向tmp
ps->capacity = newCapacity;//容量改变成新容量大小
}
ps->data[ps->top] = x;//放入x数据
ps->top++;//top往后移一个
}
void StackPrint(ST* ps)
{
int top = ps->top;
while (top)
{
printf("%d", ps->data[top - 1]);
//注意每一次打印的是栈顶的元素,而top指向的是栈顶的下一个元素,这里要减1一下
top--;
}
}
int main()
{
ST List;
SLInit(&List);
int n = 0;
scanf("%d", &n);
getchar();
int x = 0;
while (n != 0)
{
x = n % 2;
n = n / 2;
StackPush(&List, x);//每一次算出来的x都进行一下压栈
}
StackPrint(&List);
return 0;
}