[数据结构与算法分析] 栈的数组实现

前言

栈的实现比较简单,提前声明一个数组作为元素的存储空间即可。不过这就要求代码中有满栈检查,以免发生数组越界。因为现代计算机系统将栈操作作为指令结构的一部分,所以栈可能是仅次于数组的最基本的数据结构。

代码

整体代码比较简单,只需注意TopOfStack这个索引值的用法即可。

.h中的声明:

#ifndef ARRAYSTACK_H_INCLUDED
#define ARRAYSTACK_H_INCLUDED

struct StackRecord;
typedef struct StackRecord *Stack;

#define ElementType int

int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int MaxElements);
void MakeEmpty(Stack S);
void Push(ElementType X, Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);

void PrintStack(Stack S);
int StackSize(Stack S);

#endif // ARRAYSTACK_H_INCLUDED

.c文件实现

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

#define EmptyTOS -1 // which means Empty Top Of Stack.
#define MinStackSize 3

struct StackRecord {
  int Capacity;
  int TopOfStack; // TOS is a "index" which points to the top
  ElementType * Array;
};

Stack CreateStack(int MaxElements) {
  Stack S;
  if (MaxElements < MinStackSize) {
    printf("Stack size's too small.\n");
  } else {
    S = malloc(sizeof(Stack));
    if (S == NULL)
      printf("Out of space!\n");
    S->Array = malloc(MaxElements*sizeof(ElementType));
    if (S->Array == NULL)
      printf("Out of space!\n");
    S->Capacity = MaxElements;
    MakeEmpty(S);
  }
  return S;
}
int IsEmpty(Stack S) {
  return S->TopOfStack == EmptyTOS;
}
int IsFull(Stack S) {
  return S->TopOfStack >= (S->Capacity-1);
}
void MakeEmpty(Stack S) {
  S->TopOfStack = EmptyTOS;
}
void Push(ElementType X, Stack S) {
  if (IsFull(S))
    printf("Full Stack!\n");
  else
    S->Array[++S->TopOfStack] = X;
}
ElementType Top(Stack S) {
  if (!IsEmpty(S)) {
    return S->Array[S->TopOfStack];
  } else {
    printf("Empty Stack\n");
    return 0;
  }
}
void Pop(Stack S) {
  if (IsEmpty(S))
    printf("Empty Stack\n");
  else
    S->TopOfStack--;
}
ElementType TopAndPop(Stack S) {
  if (!IsEmpty(S)) {
    return S->Array[S->TopOfStack--];
  } else {
    printf("Empty Stack\n");
    return 0;
  }
}

int main()
{
  Stack S = CreateStack(100);
  for (int i = 20; i <= 60; i++) {
    Push(i,S);
  }
  while (!IsEmpty(S)) {
    printf("%d ",TopAndPop(S));
  }
  printf("\n");

  for (int i = 1; i <= 102; i++) {
    Push(i,S);
  } // should have twice "Full Stack".

  return 0;
}

测试运行结果

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值