栈:是一种思想,实现将数据以先进后出(FILO:first in last out)方式操作
一、模型:井口
二、数据类型:
//宏:
#define MAXSIZE 10
//重命名:将int取一个别名:StackType
typedef int StackType;
//栈的类型:
struct stack
{
//数据:
StackType buf[6]; //栈的元素
//方法
short top; //栈顶下标
};
三、功能:
1、初始化InitStack
2、清空栈:ClearStack
3、出栈:pop
4、进栈:push
5、判断栈为满:IsFull
6、判断栈为空:IsEmpty
7、取次栈顶
8、栈的元素个数:StackLength
四、栈的应用:撤消与恢复,记忆,递归,高级功能计算
栈的代码详解、将二进制结果取出,实现代码如下
#include<stdio.h>
//宏
#define MAXSIZE 32
#define FALSE 0
#define TRUE 1
//重命名:将char取一个别名:StackType
typedef char StackType;
typedef char BOOL;
//栈的类型;
struct st
{
//数据
StackType buf[MAXSIZE];//栈的元素
//方法
short top;//栈顶下标
};
//重命名:
typedef struct st stack;//将struct stde 类型取别:stack
/*功能:初始化栈
*函数名:InitStack
*返回值:void
*/
void InitStack(stack *p)
{
p->top=-1;
}
/*功能:判断栈为满
*函数名:IsFull
*返回值:为满——真1,非满——假0
*/
BOOL IsFull(stack *p)
{
if(MAXSIZE-1==p->top)
{
return TRUE;
}else
{
return FALSE;
}
}
/*功能:判断栈为空
* 函数名:IsEmpty
*返回值:为空——真1,非空——假0
*/
BOOL IsEmpty(stack *p)
{
if(-1==p->top)
{
return TRUE;
}else
{
return FALSE;
}
}
/*功能:进栈
*函数名:push
*返回值:成功TRUN 失败FALSE
*注:不能为满,否则进栈失败
*/
BOOL push(stack *p,StackType data)//p=&s
{
//判断栈是否为满
if(TRUE==IsFull(p))//为满
{
return FALSE;//返回失败
}
p->buf[++p->top]=data;
return TRUE;//返回成功
}
/*功能:出栈
*函数名:pop
*返回值:出栈成功TRUE 失败FALSE
*/
BOOL pop(stack *p,StackType *pd)
{
//判断是否为空,为空出栈无意义
if(TRUE==IsEmpty(p))
{
return FALSE;//出栈失败
}
*pd=p->buf[p->top--];//优先级->大于--
return TRUE;//出栈成功
}
void main()
{
//定义变量:类型 变量名
//struct st s;
struct st s;//分配空间
//初始化
InitStack(&s);
int num=0;
printf("请输入");
scanf("%d",&num);
//求二进制
while(num!=0)
{
//将余数入栈
if(FALSE==push(&s,num%2))
{
return;//结束
}
num/=2;
}
//将二进制结果取出来
char value=0;
while(FALSE!=pop(&s,&value))
{
printf("%d",value);
}
printf("\n");
}