//函數聲明: #define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #define STACK_INIT_MEMORY 100 #define STACK_GROW_MEMORY 10 typedef int ElemType; typedef struct stack { ElemType *esp; ElemType *ebp; int size; //記錄當前棧內空間最多能存幾個元素 }stack; //函數實現: void creatstack(stack *S) { S->ebp = (ElemType *)malloc(sizeof(ElemType)* STACK_INIT_MEMORY); if (S->ebp == NULL) //判斷動態內存是否開闢成功 exit(1); S->size = STACK_INIT_MEMORY; S->esp = S->ebp; } int push(stack *S, ElemType x) { if (S->esp - S->ebp >= S->size) //判斷當前棧是否已滿 { //棧滿追加空間 S->ebp = (ElemType *)realloc(S->ebp, sizeof(ElemType)*(S->size + STACK_GROW_MEMORY)); if (S->ebp == NULL) exit(1); S->esp = S->ebp + S->size; //讓棧頂指針向後偏移指向要入棧的位置 S->size += STACK_GROW_MEMORY; } *S->esp++ = x; return 1; } int pop(stack *S, ElemType *x) { if (S->esp == S->ebp) return 0; else { *x = *--S->esp; return 1; } } int getesp(stack *S, ElemType *x) { if (S->esp == S->ebp) return 0; else { *x = *(S->esp - 1); return 1; } } int stacklength(stack *S) { return S->esp - S->ebp; } void destorystack(stack *S) { if (S->ebp != NULL) //銷燬棧 free(S->ebp); } //函數測試: #include"stack.h" int main() { printf("************************************\n"); printf("*0.exit 1.creatstack *\n"); printf("*2.push 3.pop *\n"); printf("*4.getesp 5.stacklength *\n\n\n"); stack ret; ret.ebp = NULL; ElemType x; int n = 0; while (1) { printf("請選擇功能:"); scanf("%d", &n); switch (n) { case 0: destorystack(&ret); exit(1); break; case 1: if (ret.ebp != NULL) { destorystack(&ret); //若是當前已經建立了一個棧,則先銷燬在建立 } creatstack(&ret); printf("建立成功\n"); break; case 2: printf("請輸入入棧元素:"); scanf("%d", &x); push(&ret, x); printf("入棧成功\n"); break; case 3: if (pop(&ret, &x) == 0) printf("棧是空棧!\n"); else printf("彈出成功,彈出元素:%d\n", x); break; case 4: if (getesp(&ret,&x) == 0) printf("棧是空棧!\n"); else printf("棧頂元素:%d\n",x); break; case 5: printf("棧的長度:%d\n", stacklength(&ret)); break; default: printf("選擇無效\n"); break; } } system("pause"); return 0; }