#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// 栈 尽在表尾端(栈顶)进行插入和删除
// 后进先出
// 顺序栈
#define MAXSIZE 10 //数组最大容量
//顺序栈就是功能不完整的数组,栈顶相当于数组的最后一个
typedef struct STACK
{
int stacksize; //栈最大可用容量
int count; //记录当前栈的元素个数
int *top; //栈顶指针
}Sqstack, *Stack;
Stack Init_stack()
{
Stack s = malloc(sizeof(Stack));
if (s != NULL)
{
s -> top = calloc(MAXSIZE,sizeof(int));
s -> stacksize = MAXSIZE;
s -> count = -1;
return s;
}
}
bool Empty_stack(Stack S) //判空
{
return S -> count == -1; //成立 true 否则 false
}
bool Full_stack(Stack S) //是否已满
{
return S -> count == S -> stacksize -1;
}
bool Push_stack(Stack S, int DATA) //入栈
{
if(Full_stack(S))
{
return false; //栈已满
}
S -> count++; //存储的数量+1
S -> top[S -> count] = DATA;
return true;
}
bool Pop_stack(Stack S, int *elem) //出栈,并用elem返回删除的值
{
if(Empty_stack(S))
{
return false; //栈空
}
*elem = S -> top[S -> count];
S -> count--;
return true;
}
void Print_stack(Stack S) //打印栈
{
if(Empty_stack(S))
{
printf("栈空!");
}
int temp = S -> count;
for( temp; temp != -1; temp--)
{
printf("%2d", S -> top[temp]);
}
printf("\n");
}
int main()
{
Stack s = Init_stack();
int n;
printf("请输入需要转换的10进制数据:\t");
scanf("%d",&n);
while(n > 0)
{
if(Push_stack(s, n % 2) == false)
{
printf("入栈失败!\n");
return -1;
}
n /= 2;
}
printf("转换为2进制的数据为: \t");
int m;
while(!Empty_stack(s))
{
if (Pop_stack(s, &m) == false)
{
break;
}
printf("%d", m);
}
printf("\n");
Print_stack(s);
for( n = 1; n < 5; n++)
{
Push_stack(s,n);
}
Print_stack(s);
return 0;
}
结果图: