使用数组表实现的栈

my_stack_in_array.h

#ifndef MY_STACK_IN_ARRAY
#define MY_STACK_IN_ARRAY
#define elementType int


struct my_stack_in_array
{
  int capacity;
  int topOfStack;
  elementType *Array;  
};
typedef struct my_stack_in_array myStack;
typedef struct my_stack_in_array * Stack;
typedef Stack Node;

void fatalError(const char * );
int isEmpty(Stack stack);
int isFull(Stack stack);
Stack createStack(int capacity);
void disposeStack(Stack stack);
void makeEmpty(Stack stack);
void push(Stack stack, elementType X);
void pop(Stack stack);
elementType top(Stack stack);
elementType topAndpop(Stack);

#define emptyTOS (-1)
#define minStackSize (5)


#endif

my_stack_in_array.c

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

void fatelError(const char * outprint)
{
  printf(outprint);
  fflush(stdout);
  exit(EXIT_FAILURE);
}

int isEmpty(Stack stack)
{
  return stack->topOfStack == emptyTOS;
}


int isFull(Stack stack)
{
  return stack->capacity == stack->topOfStack;
}


Stack createStack(int capacity)
{
  Stack stack = (Stack)malloc(sizeof(Stack));
  if(stack == NULL)
    fatelError("can not malloc stack!\n");
  stack->capacity = capacity;
  stack->topOfStack = emptyTOS;
  stack->Array = (elementType *)malloc(sizeof(elementType)*stack->capacity);
  return stack;
}


void disposeStack(Stack stack)
{
 free(stack);
}


void makeEmpty(Stack stack)
{
  stack->topOfStack = emptyTOS;
}


void push(Stack stack, elementType X)
{
  if (isFull(stack))
    fatelError("stack is full \n");
  else
    stack->Array[++(stack->topOfStack)] = X;
}


void pop(Stack stack)
{
  if(isEmpty(stack))
    fatelError("stack is empty \n");
  else
    stack->topOfStack--;
}


elementType top(Stack stack)
{
  if(isEmpty(stack))
  {
    fatelError("stack is empty \n");
    return -1;
  }
  else
    return stack->Array[stack->topOfStack];
}


elementType topAndpop(Stack stack)
{
  if(isEmpty(stack))
  {
    fatelError("stack is empty \n");
    return -1;
  }
  return stack->Array[stack->topOfStack--];
}

my_stack_in_array_test.c

#include "my_stack_in_array.c"
#define theStackSize 20
int main()
{
  Stack stack = createStack(theStackSize);
  for(int i = 0; i < theStackSize; i++)
    push(stack, i*9);
  for(int i = 0; i < theStackSize+5; i++)
    printf("%d \n", topAndpop(stack));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值