Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int top = -1; // top 指向 Stack 最上端的元素
- int len; // Stack 的長度
- int* arr; // 儲存 Stack 的容器
- int isEmpty();
- int isFull();
- int push(int n);
- int pop();
- int isEmpty(){ // 檢查 Stack 是否是滿的
- if(top <= -1) return 1;
- else return 0;
- }
- int isFull(){ // 檢查 Stack 是否是空的
- if(top == len-1) return 1;
- else return 0;
- }
- int push(int n){ // 檢查 Stack 是否仍有空間,若有,則 push 一個值 n 進 Stack
- if(isFull() == 1){
- printf("The Stack Is Full!\n");
- return 0;
- }else{
- top++;
- arr[top] = n;
- return 1;
- }
- }
- int pop(){ // 檢查 Stack 是否為空的,若不是空的,則從 Stack 中 pop 掉一個值
- if(isEmpty() == 1){
- printf("The Stack Is Empty!\n");
- return 0;
- }else{
- top--;
- return arr[top];
- }
- }
- int main(){
- char set[5];
- char* set1 = "push";
- char* set2 = "pop";
- int num;
- printf("Enter the Capacity of the Stack: ");
- scanf("%d", &len);
- arr = malloc(len * sizeof(int) );
- re:
- scanf("%s", set);
- if(strcmp(set, set1) == 0){
- scanf("%d", &num);
- push(num);
- printf("%d\n", arr[top] );
- }else if(strcmp(set, set2) == 0)
- if(pop() ) printf("%d\n", arr[top+1] ); // 印出在 Stack 中被 pop 掉的值
- else printf("error\n");
- *set = 0;
- goto re;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement