Advertisement
lIlIlIlIIlI

Data Structure_Stack

Sep 9th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int top = -1;   // top 指向 Stack 最上端的元素
  6. int len;    // Stack 的長度
  7. int* arr;   // 儲存 Stack 的容器
  8.  
  9. int isEmpty();
  10. int isFull();
  11. int push(int n);
  12. int pop();
  13.  
  14. int isEmpty(){ // 檢查 Stack 是否是滿的
  15.     if(top <= -1)   return 1;
  16.     else    return 0;
  17. }
  18.  
  19. int isFull(){ // 檢查 Stack 是否是空的
  20.     if(top == len-1)    return 1;
  21.     else    return 0;
  22. }
  23.  
  24. int push(int n){ // 檢查 Stack 是否仍有空間,若有,則 push 一個值 n 進 Stack
  25.     if(isFull() == 1){
  26.         printf("The Stack Is Full!\n");
  27.         return 0;
  28.     }else{
  29.         top++;
  30.         arr[top] = n;
  31.         return 1;
  32.     }
  33. }
  34.  
  35. int pop(){ // 檢查 Stack 是否為空的,若不是空的,則從 Stack 中 pop 掉一個值
  36.     if(isEmpty() == 1){
  37.         printf("The Stack Is Empty!\n");
  38.         return 0;
  39.     }else{
  40.         top--;
  41.         return arr[top];
  42.     }
  43. }
  44.  
  45. int main(){
  46.     char set[5];
  47.     char* set1 = "push";
  48.     char* set2 = "pop";
  49.     int num;
  50.  
  51.     printf("Enter the Capacity of the Stack: ");
  52.     scanf("%d", &len);
  53.     arr = malloc(len * sizeof(int) );
  54.  
  55.     re:
  56.    
  57.     scanf("%s", set);
  58.     if(strcmp(set, set1) == 0){
  59.         scanf("%d", &num);
  60.         push(num);
  61.         printf("%d\n", arr[top] );
  62.     }else if(strcmp(set, set2) == 0)
  63.         if(pop() )  printf("%d\n", arr[top+1] ); // 印出在 Stack 中被 pop 掉的值
  64.     else    printf("error\n");
  65.  
  66.     *set = 0;
  67.    
  68.     goto re;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement