Advertisement
AlexLeo

Stack using C++

Nov 3rd, 2014
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. #include <stdio.h>
  2. //#include <stdlib.h>
  3. #define MAXSTACK 10
  4.  
  5. void displaySlection();
  6. void insertStack(int* stack, int* stackTop, int value);
  7. void displayStack(int* stack, int stackTop);
  8. void displayTop(int* stack, int stackTop);
  9. void deleteTop(int* stack, int* stackTop);
  10.  
  11. int main()
  12. {
  13.     int stack[MAXSTACK] = {0};
  14.     int stackTop=-1;
  15.  
  16.     int slection;
  17.     int temp;
  18.  
  19.     while (true)
  20.     {
  21.         displaySlection();
  22.         scanf("%d", &slection);
  23.  
  24.         switch(slection)
  25.         {
  26.         case 1:
  27.             printf("請輸入想插入的值(整數): ");
  28.             scanf("%d", &temp);
  29.             insertStack(stack, &stackTop, temp);
  30.             break;
  31.         case 2:
  32.             displayTop(stack, stackTop);
  33.             break;
  34.         case 3:
  35.             deleteTop(stack, &stackTop);
  36.             break;
  37.         case 4:
  38.             displayStack(stack, stackTop);
  39.             break;
  40.         case -1:
  41.             break;
  42.         default:
  43.             printf("Wrong slection, try again!\n");
  44.             break;
  45.         }
  46.  
  47.         if (slection==-1)
  48.             break;
  49.         printf("\n\n\n");
  50.     }
  51.  
  52.     //system("pause");
  53.     return 0;
  54. }
  55.  
  56. void displaySlection()
  57. {
  58.     printf("請輸入選項(-1結束)\n");
  59.     printf("\t(1)插入值至堆疊\n");
  60.     printf("\t(2)顯示堆疊頂端\n");
  61.     printf("\t(3)刪除頂端值\n");
  62.     printf("\t(4)顯示所有內容\n");
  63.     printf(" > ");
  64. }
  65.  
  66. void insertStack(int* stack, int* stackTop, int value)
  67. {
  68.     if ((*stackTop)+1 > MAXSTACK)
  69.     {
  70.         printf("錯誤, 堆疊已滿!");
  71.         return;
  72.     }
  73.  
  74.     (*stackTop)++;
  75.     stack[(*stackTop)]=value;
  76. }
  77.  
  78. void displayStack(int* stack, int stackTop)
  79. {
  80.     printf("堆疊內容為: \n");
  81.  
  82.     printf("[");
  83.     for (int i=0; i<=stackTop; i++)
  84.     {
  85.         printf(" %d ", stack[i]);
  86.     }
  87.     printf("]\n");
  88. }
  89.  
  90. void displayTop(int* stack, int stackTop)
  91. {
  92.     printf("堆疊頂端為: \n");
  93.  
  94.     printf("[ %d ]", stack[stackTop]);
  95. }
  96.  
  97. void deleteTop(int* stack, int* stackTop)
  98. {
  99.     if ((*stackTop)<=0)
  100.     {
  101.         printf("堆疊為空!");
  102.         return;
  103.     }
  104.  
  105.     stack[(*stackTop)]=0;
  106.     (*stackTop)--;
  107.     printf("堆疊頂端已刪除");
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement