順序棧的C語言實現


  1 #include <stdbool.h>
  2 #include "stdio.h"
  3 #define MAXSIZE 20
  4 #define OK 1
  5 #define ERROR 0
  6 
  7 struct sqStack{
  8     int data[MAXSIZE];
  9     int top;
 10 };
 11 
 12 /*初始化操作,建立一個空棧*/
 13 int initStack(struct sqStack *s){
 14     s->top=-1;
 15     return OK;
 16 }
 17 
 18 /*若棧存在,則銷毀*/
 19 int destoryStack(struct sqStack *s){
 20     if(s->top==-1){
 21         printf("該棧不存在\n");
 22         return ERROR;
 23     }
 24     s->top=-1;
 25     return OK;
 26 }
 27 
 28 /*清空棧*/
 29 int clearStack(struct sqStack *s){
 30     if(s->top==-1){
 31         printf("該棧不存在\n");
 32         return ERROR;
 33     }
 34     s->top=-1;
 35     return OK;
 36 }
 37 
 38 /*判斷棧是否為空*/
 39  bool isEmpty(struct sqStack *s){
 40      if(s->top==-1){
 41          return true;
 42      }
 43      return false;
 44  }
 45 
 46  /*獲取棧頂元素*/
 47 int getTop(struct sqStack *s ,int *e){
 48     if(isEmpty(s)){
 49         return ERROR;
 50     }
 51     *e=s->data[s->top];
 52      return OK;
 53 }
 54 
 55 /*壓棧*/
 56 int push(struct sqStack *s,int e){
 57     if(s->top==MAXSIZE-1){
 58         printf("該棧已滿!");
 59         return ERROR;
 60     }
 61     s->top++;
 62     s->data[s->top]=e;
 63 
 64     return OK;
 65 }
 66 
 67 /*pop*/
 68 int pop(struct sqStack *s ,int *e){
 69     if(isEmpty(s)){
 70         return ERROR;
 71     }
 72     *e=s->data[s->top];
 73     s->top--;
 74     return OK;
 75 }
 76 
 77 /*獲取長度*/
 78 int getLength(struct sqStack *s){
 79     if(isEmpty(s)){
 80         return -1;
 81     }
 82     return s->top+1;
 83 }
 84 
 85 int display(struct sqStack *s){
 86     int length=0;
 87     length=getLength(s);
 88     if(length>=0){
 89         printf("the length is %d\n",length);
 90     }
 91 
 92     if(isEmpty(s)){
 93         return ERROR;
 94     }
 95     while(s->top>=0){
 96         printf("%d\n",s->data[s->top]);
 97         s->top--;
 98     }
 99     //注意顯示結束之后需要將top移動棧頂
100     s->top=length-1;
101     return OK;
102 }
103 
104 int main(){
105     struct sqStack *myStack;
106     int data;
107     initStack(myStack);
108     //isEmpty(myStack);
109     push(myStack,1);
110     push(myStack,2);
111     push(myStack,3);
112     printf("myStack has %d eles\n",getLength(myStack));
113     display(myStack);
114 
115     pop(myStack,&data);
116     printf("the pop ele is %d\n",data);
117     printf("myStack has %d eles\n",getLength(myStack));
118     display(myStack);
119     destoryStack(myStack);
120     display(myStack);
121 
122 
123 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM