栈的动态顺序存储实现(Stack)

  • 接口参考严蔚敏老师的数据结构课本
  • 实现环境为linux

Stack.h

// ======== ADT the representation of the STACK(Sequential Storage) ======== //
#ifndef STACK_H_
#define STACK_H_
#include 

#define STACK_INIT_SIZE 5
#define STACKINCREMENT 1

#define OK 1
#define ERROR 0
#define OVERFLOW -1

typedef int Elem;

typedef struct {
	Elem *base;
	Elem *top;
	int stacksize;
	//int length;
}Stack;

//Initialize the stack
void InitStack(Stack *S);

//destroy the stack
void DestroyStack(Stack *S);

//clear the stack
void ClearStack(Stack *S);

//determine if the stack is empty
bool IsEmpty(Stack S);

//return the length of the stack
unsigned int Length(Stack S);

//return the top of the stack
Elem Top(Stack S);

//push e on the stack
bool Push(Stack *S, Elem e);

//pop the stack
bool Pop(Stack *S);

#endif

Stack.c

#include 
#include 
#include "Stack.h"
#include 
//Initialize the stack
void InitStack(Stack *S) {
	S->base = (Elem*)malloc(STACK_INIT_SIZE * sizeof(Elem));
	memset(S->base, 0, STACK_INIT_SIZE * sizeof(Elem));	
	if (!S->base)
		exit(OVERFLOW);
	S->top = S->base;
	S->stacksize = STACK_INIT_SIZE;
}

//destroy the stack
void DestroyStack(Stack *S) {
	free(S->base);
	S->stacksize = 0;
	S->base = NULL;
	S->top = NULL;
}

//clear the stack
void ClearStack(Stack *S) {
	S->top = S->base;
}
//determine if the stack is empty
bool IsEmpty(Stack S) {
	return S.top == S.base;
}

//return the length of the stack
unsigned int Length(Stack S) {
	return S.top - S.base;
}
//return the top of the stack
Elem Top(Stack S) {
	return *(S.top - 1);
}

//push e on the stack
bool Push(Stack *S, Elem e) {
	if (S->top - S->base + 1 >= S->stacksize) {
		S->base = (Elem*)realloc(S->base, (STACK_INIT_SIZE + STACKINCREMENT) * sizeof(Elem));
		S->stacksize += STACKINCREMENT;
		printf("increment\n");
	}
	if (!S->base)
		exit(OVERFLOW);
	
	*(S->top) = e;
	S->top++;
	return OK;
}

	

//pop the stack
bool Pop(Stack *S) {
	if (IsEmpty(*S)) {
		printf("fail\n");
		exit(OVERFLOW);
	}
	S->top--;
	return OK;
}

main.c

#include 
#include "Stack.h"
int main () {
	Stack S1;
	InitStack(&S1);
	Push(&S1,1);
	Push(&S1,2);
	Push(&S1,3);
	Push(&S1,4);
	Push(&S1,5);
	Stack S2;
        InitStack(&S2);
        Push(&S2,1);
        Push(&S2,2);
        Push(&S2,3);
        Push(&S2,4);
        Push(&S2,5);
	while (!IsEmpty(S2)) {
		printf("%d\n",Top(S2));
		Pop(&S2);
	}
	//Pop(&S2);
	printf("the length of the stack is %d\n",Length(S1));
	printf("the top of the stack is %d\n",Top(S1));
	Pop(&S1);
	printf("the top of the stack is %d\n",Top(S1));
	DestroyStack(&S1);
	DestroyStack(&S2);
	return 0;
}

makefile

object = main.o Stack.o

test : $(object)
	gcc -g -Wall -o test $(object) -std=c99

.PHONY : clean

clean : 
	rm -rf *.o

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