码迷,mamicode.com
首页 > 编程语言 > 详细

C语言 顺序栈

时间:2018-04-08 21:19:12      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:init   --   error   include   push   std   stdio.h   bsp   amp   

  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 }

 

C语言 顺序栈

标签:init   --   error   include   push   std   stdio.h   bsp   amp   

原文地址:https://www.cnblogs.com/Paul007/p/8747122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!