栈的应用-用栈实现八进制的顺序输出(c语言实现)

1.data.h

# ifndef _DATA_H
# define _DATA_H

typedef int ElemType;

# endif

 

2.stack.h

# ifndef _STACK_H
# define _STACK_H

# include "data.h"

# define STACK_INIT_SIZE 10
# define STACK_INCREME   10

typedef struct
{
 ElemType * base;
 ElemType * top;
 int size;
}STACK;


int Pop(STACK * s, ElemType * e);
int Push(STACK * s, ElemType * e);
void DestroyStack(STACK * s);
STACK * InitStack();
int IsEmpty(STACK * s);


# endif

 

3.stack.c

# include "stack.h"
# include <stdio.h>
# include <stdlib.h>


STACK * InitStack()
{
 STACK * s = (STACK *)malloc(sizeof(STACK));
 if(NULL == s)
  exit(0);
 s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
 if(NULL == s->base) exit(0);
 s->top = s->base;
 s->size = STACK_INIT_SIZE;

 return s;
}

void DestroyStack(STACK * s)
{
 free(s->base);
 free(s);
}

int Push(STACK * s, ElemType * e)
{
 if(s == NULL || e == NULL)
  return 0;
 if(s->top - s->base >= s->size)
 {
  s->base = (ElemType *)realloc(s->base, (s->size +
   STACK_INCREME) * sizeof(ElemType));
  if(s->base == NULL) return 0;
  s->top = s->base + s->size;
  s->size = s->size + STACK_INCREME;
 }
 * s->top ++ = * e;
 
 return 1;
}

int Pop(STACK * s, ElemType * e)
{
 if(s == NULL || e == NULL)
  return 0;
 if(s->base == s->top)
  return 0;
 * e = * --s->top;
 return 1;
}

int IsEmpty(STACK * s)
{
 return s->top == s->base ? 1 : 0;
}

 

4.main.c

# include "stack.h"
# include <stdio.h>

void main()
{
 int num = 1348;
 int temp;
 STACK * s = InitStack();
 while(num)
 {
  temp = num % 8;
  Push(s, &temp);
  num /= 8;
 }
 while(!IsEmpty(s))
 {
  Pop(s, &temp);
  printf("%d", temp);
 }
 printf("\n");

 DestroyStack(s);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值