#include<stdio.h> //栈的顺序存储
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#define MAXSIZE 100
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
//#define SElemType int
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define SElemType int
typedef int ElemType;
typedef int Status;
#define stack_size 100
#define stack_crement_size 10
typedef int Elemtype;
///声明一个栈
typedef struct Stack
{
Elemtype *top;
Elemtype *base;
int stacksize;
}sqstack;
//函数声明
void IntiStack(sqstack *s);
int Push(sqstack* s,Elemtype e);
void Pop(sqstack* s,Elemtype *e);
int StackLen(sqstack s);
int StackEmpty(sqstack* s);
void DestoryStack(sqstack* s);
//始化栈
void IntiStack(sqstack *s)
{
s->base = (Elemtype*)malloc(sizeof(Elemtype)*stack_size);
if(!s->base)
exit(0);
s->top = s->base; //设置栈为空
s->stacksize = stack_size;
}
//入栈操作
int Push(sqstack* s,Elemtype e)
{
if(s->top - s->base >= s->stacksize) //判断是否栈满
{
s->base = (Elemtype*)realloc(s->base,(s->stacksize + stack_crement_size)*sizeof(Elemtype));
if(!s->base)
exit(0);
s->top = s->base + s->stacksize; //重新设置栈顶
s->stacksize += stack_crement_size; //重新设置栈的大小
}
*(s->top) = e;
s->top++;
return 1;
}
//出栈操作
void Pop(sqstack* s,Elemtype *e)
{
if(s->top == s->base) //如果栈为空
return;
*e = *--(s->top);
}
//求栈的当前容量
int StackLen(sqstack s)
{
return s.top - s.base;
}
//清空栈
int StackEmpty(sqstack* s)
{
return (s->stacksize == 0);
}
//销毁栈
void DestoryStack(sqstack* s)
{
int i,len;
len = s->stacksize;
for( i = 0; i <len; i++)
{
s->base++;
free(s->base);
}
s->base = s->top = NULL;
s->stacksize = 0;
}
int main(void)
{
sqstack s;
int i,c,k;
int j = 0; //用来记录转化后的8进制数位数
int N;
printf("请输入一个十进制数:");
scanf("%d",&N);
int W = N;
IntiStack(&s); //初始化栈
while(N != 0) //除k取余法转换,并把余数入栈
{
k = N%8;
Push(&s,k);
N = N/8;
j++;
}
printf("十进制数 %d 转化为八进制数为: ",W);
for( i=0; i<j; i++)
{
Pop(&s,&c);
printf("%d",c);
}
//DestoryStack(&s);
printf("\n");
return 0;
}
函数运行结果
今天的文章判断出栈顺序是否正确_栈的初始化是什么意思[通俗易懂]分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/88667.html