数据结构与算法---栈

来源:互联网 发布:音频信号发生器软件 编辑:程序博客网 时间:2024/05/16 02:09

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

enum boolean {FALSE,TRUE};
typedef enum boolean Bool;
typedef int ElementsType;

struct stack
{
 int top;
 ElementType *elements;
 int MaxSize;
};

typedef struct stack Stack;

void InitStack(Stack *,int sz);
void FreeStack(Stack *);
int Push(Stack *,ElementType);
ElementType Pop(Stack *);
ElementType GetTop(Stack*);
void MakeEmpty(Stack *);
Bool IsEmpty(Stack *S);
Bool IsFull(Stack *S);

#include"stack.h"

void FreeStack(Stack *S)
{
 free(S->elements);
}

void MakeEmpty(Stack *S)
{
 S->top = -1;
}

Bool IsEmpty(Stack *S)
{
 return (Bool)(S->top == -1);
}

Bool IsFull(Stack *S)
{
 return (Bool)(S->top == S->MaxSize-1);
}

void InitStack(Stack *S,int sz)
{
 S->MaxSize = sz;
 S->elements = (ElementType *)malloc(sizeof(ElementType ) * S->MaxSize);
 S->top = -1;
}

int Push(Stack *S,ElementType item)
{
 if(!IsFull(S))
 {
  S->elements[++(S->top)] = item;
  return 0;
 }
 else
 return -1;
}

ElementType Pop(Stack *S)
{
 if(!IsEmpty(S))
  return S->elments[(S->top)--];
 else
 {
  printf("stack is empty\n");
  exit(1);
 }
}

ElementType GetTop(Stack *S)
{
 if(!IsEmpty(S))
  return S->elements[S->top];
 else
 {
  printf("stack is empty\n");
  exit(1);
 }
}

 

 

0 0
原创粉丝点击