Stack.h

#ifndef _STACK_H
#define _STACK_H

#include

#define MALLOC(n,type)  \
        ((type*)malloc((n)*sizeof(type)))
#define INCREASE_SIZE 10
#define STACK_SIZE 20

typedef  char StackElement;//StackElement类型根据用户需求确定

typedef enum { OK = 1,
               ERROR = 0 } Status;

typedef struct{
  StackElement *pBase;
  StackElement *pTop;
  unsigned stackSize;//栈容量
} Stack;

Status BuildAStack(Stack *pStack);//构建一个栈
Status DestructAStack(Stack *pStack);//销毁一个栈
bool IsEmpty(Stack *pStack);//判断栈是否为空
bool IsFull(Stack *pStack);//判断栈是否为满
unsigned LenOfStack(Stack *pStack);//栈已储存数据的长度
Status CleanAStack(Stack *pStack);//清空一个栈
Status IncreaseASTack(Stack *pStack);//增加栈容量
Status PushIntoStack(Stack *pStack, StackElement stackElement);//数据入栈
Status PopFromStack(Stack *pStack,StackElement *popElement);//数据出栈
Status GetTopOfStack(Stack *pStack,StackElement *topElement);//获得栈顶数据但数据不出栈

#endif

Stack.c

#include
#include
#include
#include
#include "Stack.h"

Status BuildAStack(Stack *pStack){
  pStack->pBase = MALLOC(STACK_SIZE, StackElement);
  if(pStack->pBase==NULL){
    return ERROR;
  }
  pStack->pTop=pStack->pBase;//一开始忽略了这一步
  pStack->stackSize = STACK_SIZE;
  return OK;
}

Status DestructAStack(Stack *pStack){
  free(pStack->pBase);
  free(pStack);
  pStack = NULL;
  return OK;
}

bool IsEmpty(Stack *pStack){
  int len = LenOfStack(pStack);
  if(len==0){
    return true;
  }
  return false;
}

bool IsFull(Stack *pStack){
  int len = LenOfStack(pStack);
  if(len==pStack->stackSize){
    return true;
  }
  return false;
}

unsigned LenOfStack(Stack *pStack){
  return pStack->pTop - pStack->pBase;
}

Status CleanAStack(Stack *pStack){
  pStack->pTop = pStack->pBase;
  return OK;
}

Status IncreaseASTack(Stack *pStack){
  pStack->pBase = (StackElement *)realloc(pStack->pBase, INCREASE_SIZE * sizeof(StackElement));
  if(pStack->pBase==NULL){
    return ERROR;
  }
  pStack->pTop = pStack->pBase + pStack->stackSize;
  pStack->stackSize += INCREASE_SIZE;
  return OK;
}

Status PushIntoStack(Stack *pStack, StackElement stackElement){
  if(IsFull(pStack)){
    IncreaseASTack(pStack);
  }
  *(pStack->pTop) = stackElement;
  pStack->pTop++;
  return OK;
}

Status PopFromStack(Stack *pStack,StackElement *popElement){
  if(IsEmpty(pStack)){
    return ERROR;
  }
  pStack->pTop--;
  *popElement = *(pStack->pTop);
  return OK;
}

Status GetTopOfStack(Stack *pStack,StackElement *topElement){
  if(IsEmpty(pStack)){
    return ERROR;
  }
  *topElement = *(pStack->pTop-1);
  return OK;
}

main.c(此处为字符串反转的简单例子)

#include
#include "Stack.h"

int main(int argc,char *argv[]){
  Stack b;
  char ch;
  BuildAStack(&b);
  printf("Please enter a string: ");
  while(ch=getchar(),ch!='\n'&&ch!=EOF){
    PushIntoStack(&b, ch);
  }
  while (!IsEmpty(&b)){
    PopFromStack(&b, &ch);
    printf("%c", ch);
  }
  DestructAStack(&b);
  return 0;
}

你可能感兴趣的:(栈)