栈(下)

栈(下)

2、静态存储

2.1类型定义及说明


#include "stdafx.h"


#include "malloc.h"


#include "stdlib.h"


#define OK 1


#define ERROR -1


#define OVERFLOW -2


#define STACK_INIT_SIZE 100


#define STACKINCREMENT 10

typedef int Status;
typedef int ElemType;

2.2存储方式

利用C语言库函数中的malloc和realloc函数可以对栈进行动态分配或在分配内存存储,其分配的是一组连续的内存空间。

2.2.1动态栈的定义
typedef struct Stack
{
  ElemType *top;
  ElemType *base;
  int stacksize;
  int length;
}Sqstack;
2.2.2栈的初始化
Status InitStack(Sqstack &S) 
{
  S.base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
  if (!S.base)return ERROR;
  S.top = S.base;
  S.stacksize = STACK_INIT_SIZE;
  S.length = 0;
  return OK;
}//栈的初始化
2.2.3圧栈
Status Push(Sqstack &S, ElemType e)
{
  if (S.top - S.base >= S.stacksize - 1)
  {
      S.base = (ElemType *)realloc(S.base,(STACK_INIT_SIZE + STACKINCREMENT) * sizeof(ElemType));
      if (!S.base)return ERROR;
      S.stacksize += STACKINCREMENT;
  }
  *S.top = e;
  S.top++;//栈顶指针加一,e成为新的栈顶
  S.length++;
  return OK;
}
2.2.4出栈
Status Pop(Sqstack &S, ElemType &e)
{
  if (S.top == S.base)
  {
      printf("栈已经为空!");
      return ERROR;//栈空,返回错误
  }
  else
  {
      S.top--;
      S.length--;
      e = *S.top;
      return OK;
  }
}/*出栈*/
2.2.5遍历
void Travel(Sqstack S) 
{
  if (S.top == S.base) 
  {
      printf("栈空!");
  }
  else 
  {
      for (int i = 1; i < S.length; i++)
      {
          int a, b;
          a = *S.base;
          b = *(S.top--);
          printf("栈底:%d,栈顶:%d ,位置:%d\n\r", a ,b,S.length-i);
      }
  }
}
2.2.6主函数
int main()
{
  Sqstack S;
  int e;
  InitStack(S);
  for (int i = 1; i < 20; i++)
  {
      Push(S, 2*i);
  }
  Travel(S);
  Pop(S,e);
  printf("栈顶元素:%d", e);
    return 0;
}

2.3调试结果

F:\调试结果.jpg

下一节将实现栈的链式存储。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值