[每日C] 以陣列實作堆疊概念
完整原始碼:
#include <stdio.h> //#include <stdlib.h> #define MAXSTACK 10 void displaySlection(); void insertStack(int* stack, int* stackTop, int value); void displayStack(int* stack, int stackTop); void displayTop(int* stack, int stackTop); void deleteTop(int* stack, int* stackTop); int main() { int stack[MAXSTACK] = {0}; int stackTop=-1; int slection; int temp; while (true) { displaySlection(); scanf("%d", &slection); switch(slection) { case 1: printf("請輸入想插入的值(整數): "); scanf("%d", &temp); insertStack(stack, &stackTop, temp); break; case 2: displayTop(stack, stackTop); break; case 3: deleteTop(stack, &stackTop); break; case 4: displayStack(stack, stackTop); break; case -1: break; default: printf("Wrong slection, try again!\n"); break; } if (slection==-1) break; printf("\n\n\n"); } //system("pause"); return 0; } void displaySlection() { printf("請輸入選項(-1結束)\n"); printf("\t(1)插入值至堆疊\n"); printf("\t(2)顯示堆疊頂端\n"); printf("\t(3)刪除頂端值\n"); printf("\t(4)顯示所有內容\n"); printf(" > "); } void insertStack(int* stack, int* stackTop, int value) { printf("*(stackTop)=%d\n", *(stackTop)); if ((*stackTop)+1 > MAXSTACK-1) /* "+1"指的是下一個,"-1"是因為Array Index*/ { printf("錯誤, 堆疊已滿!"); } else { (*stackTop)++; stack[(*stackTop)]=value; } } void displayStack(int* stack, int stackTop) { printf("堆疊內容為: \n"); printf("["); for (int i=0; i<=stackTop; i++) { printf(" %d ", stack[i]); } printf("]\n"); } void displayTop(int* stack, int stackTop) { printf("堆疊頂端為: \n"); printf("[ %d ]", stack[stackTop]); } void deleteTop(int* stack, int* stackTop) { if ((*stackTop)<0) { printf("堆疊為空!"); return; } stack[(*stackTop)]=0; (*stackTop)--; printf("堆疊頂端已刪除"); }
終端輸出:
... 請輸入選項(-1結束) (1)插入值至堆疊 (2)顯示堆疊頂端 (3)刪除頂端值 (4)顯示所有內容 > 1 請輸入想插入的值(整數): 3 … > 4 堆疊內容為: [ 1 2 3 ] ... > 2 堆疊頂端為: [ 3 ] … > 3 堆疊頂端已刪除 ... > 4 堆疊內容為: [ 1 2 ] ... > -1 Process returned 0 (0x0) execution time : 48.998 s Press ENTER to continue.
Ps. 點點(…)為縮寫,實際執行時並不會出現