数据结构中栈的相关操作

#include<stdio.h>

#include<stdlib.h>

#define MAXNUM 15

#define INIT_SIZE 50

#define INCREMENT 20

#define OK 2

#define ERROR 0

#define OVERFLOW -1

#define TRUE 1

#define FALSE 0

typedef int ElemType;

typedef int Status;

                   

typedef struct {          //定义顺序栈的存储结构

       ElemType *base;

       ElemType *top;

       int stacksize;

}SqStack;                //顺序栈



Status InitStack(SqStack&S){   //构造一个空栈S

       S.base=(ElemType *)malloc(INIT_SIZE*sizeof(ElemType));

       if(!S.base)exit(OVERFLOW);

       S.top=S.base;

       S.stacksize=INIT_SIZE;

       return OK;

}



Status Push(SqStack&S,ElemType e){    //插入e为新的栈顶元素

       if(S.top-S.base>=S.stacksize){

              S.base=(ElemType*)realloc(S.base,(S.stacksize+INCREMENT)*sizeof(ElemType));

       if(!S.base)exit(OVERFLOW);

       S.top=S.base+S.stacksize;

       S.stacksize+=INCREMENT;

       }

       *S.top++ = e;

       return OK;

}



Status Pop(SqStack&S,ElemType &e){    //若栈不空,则删除S的栈顶元素 

       if(S.top==S.base)return ERROR;

       e=*--S.top;

       return OK;

}



Status GetTop(SqStackS,ElemType e){  //获取栈顶元素

       if(S.top==S.base)return ERROR;

       e=*(S.top-1);

       return OK;

}



void printstack(SqStackS){          //遍历输出栈内元素

       ElemType e;

       do{

              e=*S.top-1;

              printf("%c ",e);

              S.top--;

       }while(S.base==S.top);

}



StatusEmptystack(SqStack S){      //判断栈是否为空,为空返回1,否则返回0

       if(S.top==S.base)

              return 1;

       else

              return 0;

}



StatusClearstack(SqStack &S){         //清空栈内元素

       S.top=S.base;

       return OK;

}



StatusDestroystack(SqStack &S){     //销毁栈

       free(S.base);

       return OK;

}



void conversion(StatusN){     //十进制转换为八进制

       SqStack S;

       Status e;

       InitStack(S);

       while(N){

              Push(S,N%8);

              N=N/8;

       }

       while(!Emptystack(S)){

              Pop(S,e);

              printf("%d",e);

       }

}



int main()        //主函数

{

       Status N;

       printf("请输入一个十进制整数:\n");

       scanf("%d",&N);

       printf("该十进制整数所对应八进制数为:\n");

       conversion(N);

       return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值