這個棧是帶有表頭的棧。實現棧的一些規范操作,初始化,插入,刪除等。包括兩個頭文件Stack.h,fatal.h,庫函數Stack.c,測試函數TestStack.c。頭文件放的都是函數聲明,庫函數Stack.c放的的函數的定義。
Stack.h
typedef int ElementType; #ifndef _Stack_H #include<stdbool.h> struct Node; typedef struct Node *PtrToNode; typedef PtrToNode Stack; bool IsEmpty(Stack S);//判斷棧是否為空 Stack CreatStack(void);//初始化一個棧 void Pop(Stack S);//對棧進行刪除工作,只能彈出棧頂元素 void MakeEmpty(Stack S);//使得一個棧制空 void Push(ElementType X, Stack S); ElementType Top(Stack S); void DisposeStack(Stack S); void PrintStake(Stack S); #endif // !_Stack_H
fatal.h
#include<stdio.h> #include<stdlib.h> #define Error(Str) FatalError(Str) #define FatalError(Str) fprintf(stderr, "%s\n", Str), exit(1);
Stack.c
#include "Stack.h" #include<stdlib.h> #include<stdio.h> #include"fatal.h" //結構體定義 struct Node { ElementType Element; PtrToNode Next; }; bool IsEmpty(Stack S) { return S->Next == NULL; } //初始化一個棧 Stack CreatStack(void) { Stack S; S = malloc(sizeof(struct Node)); if (S == NULL) FatalError("Out of Space!") S->Next = NULL; MakeEmpty(S);//保證棧是個空棧 return S; } //對棧進行刪除工作,只能刪除頂部元素 void Pop(Stack S) { PtrToNode FirstCell; if (IsEmpty(S)) Error("Empty Stack!") else { FirstCell = S->Next; S->Next = S->Next->Next; free(FirstCell); } } //使得一個棧制空 void MakeEmpty(Stack S) { if (S==NULL) Error("Must use CreatStake first") else { while (!IsEmpty(S)) Pop(S); } } //往棧S添加一個元素X void Push(ElementType X, Stack S) { PtrToNode TmpCell; TmpCell = malloc(sizeof(struct Node)); if (TmpCell==NULL) FatalError("Out of Space!") else { TmpCell->Element = X; TmpCell->Next = S->Next; S->Next = TmpCell; } } ElementType Top(Stack S) { if (!IsEmpty(S)) return S->Next->Element; Error("Empty Space"); return 0;/*Return value used to avoid warning*/ } void DisposeStack(Stack S) { MakeEmpty(S); free(S); } //打印棧,棧也沒了 void PrintStake(Stack S) { while (!IsEmpty(S)) { printf("%d ", Top(S)); Pop(S); } }
TestStack.c
#include "Stack.h" #include<stdio.h> #include<time.h> #include<stdlib.h> int main() { Stack S; S = CreatStack(); printf("隨機生成多少位數:"); long amount; scanf_s("%d", &amount); srand((unsigned)time(NULL)); for (long i = 0; i < amount; i++) Push(rand() % 1000,S);//插入元素 PrintStake(S); DisposeStack(S);//釋放棧 }