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

前言

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

代码

整体代码比较简单,只需注意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;
}

测试运行结果

[数据结构与算法分析] 栈的数组实现_第1张图片

你可能感兴趣的:(数据结构,栈)