1. 程式人生 > >棧的順序表(C語言)

棧的順序表(C語言)

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

struct Stack;
typedef struct Stack *Stack;
typedef int ElementType;

#define EmptyOTS -1
#define MinStackSize 5

//棧的資料結構
struct Stack
{
    int Capacity;
    int TopOfStack;
    int *Array;
};

// 申請兩次記憶體,第一次為棧的Capacity和TopOfStack申請,第二次為Array申請
Stack CreateStack(int
MaxElements) { Stack S; if (MaxElements < MinStackSize) { printf("stack size if too small!\n"); return NULL; } // 第一次申請記憶體 S = malloc(sizeof(struct Stack)); if (S == NULL) { printf("Stack malloc failed!\n"); return NULL; } // 為array申請記憶體
S->Array = malloc(sizeof(ElementType) * MaxElements); if (S->Array == NULL) { printf("S->Array malloc failed!\n"); return NULL; } // 設定最大長度和初始化棧頂 S->Capacity = MaxElements; S->TopOfStack = EmptyOTS; return S; } // 對應建立棧時申請的記憶體,對應釋放記憶體,注意釋放順序
void FreeStack(Stack S) { if (S != NULL) { free(S->Array); free(S); } } // 判斷棧是否為滿棧 int IsFull(Stack S) { return S->TopOfStack == S->Capacity; } // 判斷棧是否為空棧 int IsEmpty(Stack S) { return S->TopOfStack == EmptyOTS; } // 新增元素 void Push(ElementType X, Stack S) { if (IsFull(S)) { printf("stack is full\n"); return; } S->TopOfStack++; S->Array[S->TopOfStack] = X; } // pop操作無需free void Pop(Stack S) { if (IsEmpty(S)) { printf("stack is empty, cann't pop\n"); return; } S->TopOfStack--; } //取棧頂的元素 ElementType Top(Stack S) { if (IsEmpty(S)) { printf("empty stack\n"); return 0; } return S->Array[S->TopOfStack]; } // 列印棧的所有元素,從棧底向棧頂列印 void PrintStack(Stack S) { if (IsEmpty(S)) { printf("stack is empty\n"); return; } for (int i = 0; i <= S->TopOfStack; i++) { printf("%d\n", S->Array[i]); } } int main(int argc, char const *argv[]) { Stack S = CreateStack(5); for (int i = 1; i < 5; i++) { Push(i, S); } PrintStack(S); Pop(S); PrintStack(S); printf("%d\n", Top(S)); return 0; }