/* * SeqStack.h * * Created on: 2019年8月1日 * Author: Administrator */ #ifndef SEQSTACK_H_ #define SEQSTACK_H_ //數組去模擬棧的順序存儲, 有數組的後面模擬棧頂 ,避免數據頻繁移動 #define MAX_SIZE 1024 #define SEQ_STACK_TRUE 1 #define SEQ_STACK_FALSE 0 typedef struct SEQSTACK { void *data[MAX_SIZE]; int size; } SeqStack; //棧的初始化 SeqStack *Init_SeqStack(); //入棧 void Push_SeqStack(SeqStack *stack, void *data); //返回棧頂元素 void *Top_SeqStack(SeqStack *stack); //出棧 void Pop_SeqStack(SeqStack *stack); //判斷是否爲空 int IsEmpty(SeqStack *stack); //返回棧中元素個數 int Size_SeqStack(SeqStack *stack); //清空棧 void Clear_SeqStack(SeqStack *stack); //銷燬 void FreeSpace_SeqStack(SeqStack *stack); #endif /* SEQSTACK_H_ */
/* * SeqStack.c * * Created on: 2019年8月1日 * Author: Administrator */ #include "SeqStack.h" #include <stdlib.h> #include <stdio.h> #include <string.h> //棧的初始化 SeqStack *Init_SeqStack() { SeqStack *stack = (SeqStack *)malloc(sizeof(SeqStack)); for(int i = 0; i < MAX_SIZE; i++){ stack->data[i] = NULL; } stack->size = 0; return stack; } //入棧 void Push_SeqStack(SeqStack *stack, void *data) { if(stack == NULL){ return; } if(stack->size == MAX_SIZE) { return; } if(data == NULL){ return; } stack->data[stack->size] = data; stack->size++; } //返回棧頂元素 void *Top_SeqStack(SeqStack *stack) { if(stack == NULL){ return NULL; } if(stack->size == 0){ return NULL; } return stack->data[stack->size-1]; } //出棧 void Pop_SeqStack(SeqStack *stack) { if(stack == NULL){ return; } if(stack->size == 0){ return; } stack->data[stack->size-1] = NULL; stack->size--; } //判斷是否爲空 int IsEmpty(SeqStack *stack) { if(stack == NULL){ return -1; } if(stack->size == 0){ return SEQ_STACK_TRUE; } return SEQ_STACK_FALSE; } //返回棧中元素個數 int Size_SeqStack(SeqStack *stack) { return stack->size; } //清空棧 void Clear_SeqStack(SeqStack *stack) { if(stack == NULL){ return; } for(int i = 0;i < stack->size; i++){ stack->data[i] = NULL; } stack->size = 0; } void FreeSpace_SeqStack(SeqStack *stack){ if(stack == NULL){ return; } free(stack); }
/* * main.c * * Created on: 2019年8月1日 * Author: Administrator */ #include "SeqStack.h" #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct PERSON { char name[64]; int age; } Person; int main(){ printf("棧 \n"); //建立棧 SeqStack *stack = Init_SeqStack(); //建立數據 Person p1 = {"Jarvis1", 11}; Person p2 = {"Jarvis2", 12}; Person p3 = {"Jarvis3", 13}; Person p4 = {"Jarvis4", 14}; Person p5 = {"Jarvis5", 15}; //入棧 Push_SeqStack(stack, &p1); Push_SeqStack(stack, &p2); Push_SeqStack(stack, &p3); Push_SeqStack(stack, &p4); Push_SeqStack(stack, &p5); //輸出 while(Size_SeqStack(stack) > 0) { //訪問棧頂元素 Person *person = (Person *)Top_SeqStack(stack); printf("Name: %s, Age: %d \n", person->name, person->age); //彈出棧頂元素 Pop_SeqStack(stack); } //釋放內存 FreeSpace_SeqStack(stack); system("pause"); return 0; }