本文用C语言描述栈(数组方法实现),以下是源码:
#include "stack_array.h" PtrToStack CreatStack(uint32_t size) { PtrToStack S; if (size < MIN_SIZE) { printf("Stack size is too small!\r\n"); return NULL; } S = (PtrToStack)malloc(sizeof(StackType)); if (S == NULL) { printf("Out of space!\r\n"); return NULL; } S->Capacity = size; S->TopOfStack = EMPTY_TOS; S->Element = malloc((sizeof(ElementType))*size); if (S->Element == NULL) { printf("Out of space!\r\n"); return NULL; } return S; } bool DisposeStack(PtrToStack S) { if (S != NULL) { free(S->Element); free(S); } return true; } bool IsEmpty(PtrToStack S) { return (S->TopOfStack <= EMPTY_TOS); } bool IsFull(PtrToStack S) { return (S->TopOfStack >= (S->Capacity-1)); } bool MakeEmpty(PtrToStack S) { S->TopOfStack = EMPTY_TOS; return true; } bool Push(PtrToStack S, ElementType X) { if (IsFull(S)) { printf("Stack if full!\r\n"); return false; } S->TopOfStack += 1; *((S->Element) + (S->TopOfStack)) = X; return true; } ElementType Top(PtrToStack S) { ElementType WrongRet; if (IsEmpty(S)) { memset(&WrongRet, 0, sizeof(ElementType)); return WrongRet; } return *(S->Element + S->TopOfStack); } bool Pop(PtrToStack S) { if (IsEmpty(S)) { printf("Empty stack!\r\n"); return false; } S->TopOfStack--; return true; } ElementType TopAndPop(PtrToStack S) { ElementType ret; if (IsEmpty(S)) { memset(&ret, 0, sizeof(ElementType)); return ret; } ret = *(S->Element + S->TopOfStack); S->TopOfStack--; return ret; } bool PrintAllNode(PtrToStack S) { uint32_t ElementCnt = 0; int32_t Top = (S->TopOfStack); while (Top > EMPTY_TOS) { printf("No %d element is %c\r\n", ++ElementCnt, (*(S->Element + Top)).Ch); Top--; } printf("******** End ********\r\n\n"); return true; }
#ifndef __STACK_ARRAY_H_ #define __STACK_ARRAY_H_ #include <stdbool.h> #include <stdint.h> #include <malloc.h> #include <stdbool.h> #include <stdio.h> #include <memory.h> #define MIN_SIZE (1) #define EMPTY_TOS (-1) typedef union { char Ch; uint16_t Index; double Value; } ElementType; typedef struct { ElementType *Element; int32_t TopOfStack; int32_t Capacity; } StackType; typedef StackType *PtrToStack; PtrToStack CreatStack(uint32_t size); bool DisposeStack(PtrToStack S); bool IsEmpty(PtrToStack S); bool IsFull(PtrToStack S); bool MakeEmpty(PtrToStack S); bool Push(PtrToStack S, ElementType X); ElementType Top(PtrToStack S); bool Pop(PtrToStack S); ElementType TopAndPop(PtrToStack S); bool PrintAllNode(PtrToStack S); #endif