栈的数组实现

数据结构与算法分析——c语言描述 第三章  栈的数组实现


stack.h

typedef int ElementType;
#ifndef _stack_h
#define _stack_h

struct StackRecord;
typedef struct StackRecord *Stack;

int IsEmpty(Stack s);
int IsFull(Stack s);
Stack CreatStack(int MaxElements);
void DisposeStack(Stack s);
void MakeEmpty(Stack s);
void Push(ElementType X, Stack s);
ElementType Top(Stack s);
void Pop(Stack s);
ElementType TopAndPop(Stack s);

#endif

stack.c

#include"stack.h"
#include<stdlib.h>
#include"fatal.h"

#define EmptyTOS (-1)
#define MinStackSize (5)

struct StackRecord {
	int Capacity;
	int TopOfStack;
	ElementType *Array;
};

int IsEmpty(Stack s) {
	return s->TopOfStack == EmptyTOS;
}

int IsFull(Stack s) {
	return s->TopOfStack - 1 == s->Capacity;
}

Stack CreatStack(int MaxElements) {
	Stack s;
	if (MaxElements < MinStackSize)
		Error("Stack size is too small");
	s = malloc(sizeof(struct StackRecord));
	if (s == NULL)
		Error("out of space");
	else {
		s->Array = malloc(sizeof(ElementType)*MaxElements);
		if(s->Array==NULL)
			Error("out of space");
		else {
			s->Capacity = MaxElements;
			MakeEmpty(s);
		}
	}
	return s;
}

void DisposeStack(Stack s) {
	if (s != NULL) {
		free(s->Array);
		free(s);
	}
}

void MakeEmpty(Stack s) {
		s->TopOfStack = EmptyTOS;
}



void Push(ElementType X, Stack s) {
	if(IsFull(s))
		Error("Full stack");
	s->Array[++s->TopOfStack] = X;
}

ElementType Top(Stack s) {
	if (IsEmpty(s))
		Error("Empty stack");
	return s->Array[s->TopOfStack];
}

void Pop(Stack s) {
	if(IsEmpty(s))
		Error("Empty stack");
	s->TopOfStack--;
}

ElementType TopAndPop(Stack s) {
	if (IsEmpty(s))
		Error("Empty stack");
	return s->Array[s->TopOfStack--];
}

main.c

#include"stack.h"
#include<stdio.h>
int main() {
	Stack s = CreatStack(12);
	Push(233333, s);
	printf("%d", TopAndPop(s));
}


你可能感兴趣的:(栈的数组实现)