基於 Gitee 搭建個人網站-入門教程
阿新 • • 發佈:2022-03-13
1 //SeqStack.h 2 3 4 5 6 7 #ifndef SEQSTACK_H 8 #define SEQSTACK_H 9 10 11 #include<stdlib.h> 12 #include<stdio.h> 13 //陣列去模擬棧的順序儲存 14 #define MAX_SIZE 1024 15 #define SEQSTACK_TRUE 1 //棧為空 16 #define SEQSTACK_FALSE 0 //棧非空 17 18 typedef struct SEQSTACK { 19 20 void* data[MAX_SIZE];21 int size; 22 23 }SeqStack; 24 25 26 //初始化棧 27 SeqStack* Init_SeqStack(); 28 //入棧 29 void Push_SeqStack(SeqStack* stack,void* data); 30 //返回棧頂元素 31 void* Top_SeqStack(SeqStack* stack); 32 //出棧 33 void Pop_SeqStack(SeqStack* stack); 34 //判斷是否為空 35 int IsEmpty_SeqStack(SeqStack* stack); 36 //返回棧中元素的個數 37 intSize_SeqStack(SeqStack* Stack); 38 //清空棧 39 void Clear_SeqStack(SeqStack* stack); 40 //銷燬 41 void FreeSpace_SeqStack(SeqStack* stack); 42 43 44 45 46 #endif
1 //SeqStack.c 2 3 4 5 #include"SeqStack.h" 6 //#include<stdlib.h> 7 8 9 10 11 //初始化棧 12 SeqStack* Init_SeqStack() { 13 SeqStack* stack = (SeqStack*)malloc(sizeof(SeqStack)); 14 for (int i = 0; i < MAX_SIZE; i++) { 15 stack->data[i] = NULL; 16 17 } 18 stack->size = 0; 19 return stack; 20 } 21 22 23 //入棧 24 void Push_SeqStack(SeqStack* stack, void* data) { 25 if (stack == NULL) { 26 return; 27 } 28 if (data == NULL) { 29 return; 30 } 31 if (stack->size == MAX_SIZE) { 32 return; 33 } 34 stack->data[stack->size] = data; 35 stack->size++; 36 37 return; 38 } 39 40 41 //返回棧頂元素 42 void* Top_SeqStack(SeqStack* stack) { 43 if (stack == NULL) { 44 return NULL; 45 } 46 if (stack->size == 0) { 47 return NULL; 48 } 49 50 return stack->data[stack->size-1]; 51 52 } 53 //出棧 54 void Pop_SeqStack(SeqStack* stack) { 55 if (stack==NULL) { 56 return; 57 } 58 if (stack->size == 0) { 59 return; 60 } 61 stack->data[stack->size - 1] = NULL; 62 stack->size--; 63 } 64 //判斷是否為空 65 int IsEmpty_SeqStack(SeqStack* stack) { 66 if (stack == NULL) { 67 return -1; 68 } 69 if (stack->size == 0) { 70 return SEQSTACK_TRUE; 71 } 72 return SEQSTACK_FALSE; 73 } 74 //返回棧中元素的個數 75 int Size_SeqStack(SeqStack* Stack) { 76 return Stack->size; 77 } 78 //清空棧 79 void Clear_SeqStack(SeqStack* stack) { 80 if (stack == NULL) { 81 return; 82 } 83 for (int i = 0; i < stack->size; i++) { 84 stack->data[i] = NULL; 85 86 } 87 stack->size = 0; 88 return; 89 } 90 //銷燬 91 void FreeSpace_SeqStack(SeqStack* stack) { 92 if (stack == NULL) { 93 return; 94 } 95 free(stack); 96 return; 97 }
1 //main1.c 2 3 4 5 6 #include"SeqStack.h" 7 8 //人結構體 9 typedef struct PERSION { 10 char name[64]; 11 int age; 12 }Persion; 13 int main(void) { 14 //建立棧 15 SeqStack* stack = Init_SeqStack(); 16 //建立資料 17 Persion p1 = { "p1",1 }; 18 Persion p2 = { "p2",2 }; 19 Persion p3 = { "p3",3 }; 20 //入棧 21 Push_SeqStack(stack,&p1); 22 Push_SeqStack(stack,&p2); 23 Push_SeqStack(stack,&p3); 24 //輸出 25 while(Size_SeqStack(stack)>0) { 26 //訪問棧元素 27 Persion* persion=(Persion*)Top_SeqStack(stack); 28 printf("Name:%s Age: %d\n",persion->name,persion->age); 29 //彈出棧頂元素 30 Pop_SeqStack(stack); 31 } 32 //釋放記憶體 33 FreeSpace_SeqStack(stack); 34 return 0; 35 36 }