复习(数据结构):栈:c语言:动态数组

 /***************************/
 /***************************/
 /***************************/
#include <stdio.h>
#include <stdlib.h>

#define  Error(Str) FatalError(Str)
#define  FatalError(Str) fprintf(stderr,"%s\n",Str),exit(1)


#define  EmptyPos  (-1)
#define  MiStackSize (5)
#define  StackIncrement  (2) 

typedef int ElemType;

//#ifndef _Stack_h
//#define _Stack_h

 typedef struct{
     ElemType Capacity;
     ElemType Top;
     ElemType *Array;
 }SqStack;

 /**
  * 1.Top=-1,如果是空栈
  * 2. 元素x入栈,(1)top+1(2)stack[s.top]=x,是入栈的数
  * 3. 元素x出栈(1)stack[s.top]=x;(2)top-1;
  */


 int IsEmpty(SqStack s);
 int IsFull(SqStack s);
 SqStack* CreatStack(int Init_MaxElements );
 void DisposeStack(SqStack* s);
 void Push(ElemType x,SqStack* s);
 ElemType Top(SqStack s);
 void Pop(SqStack s);
 ElemType TopAndPop(SqStack S);

//#endif


 /***********************************/

 int  IsEmpty(SqStack s){
     return s.Top==EmptyPos; // top是否是-1
 }
 int IsFull(SqStack s){
     return s.Top==s.Capacity-1;
 }
 void  MakeEmpty(SqStack *s){
     s->Top=EmptyPos;
 }

 SqStack* CreatStack(int Init_MaxElements ){
     SqStack *s;
     if(Init_MaxElements < MiStackSize){
        Error("stack size is too small!");
     }

     if(!(s->Array=(ElemType *)malloc(Init_MaxElements*sizeof(ElemType))))
         FatalError("out of space");

     s->Capacity=Init_MaxElements;
     MakeEmpty(s);
 }

 void  void DisposeStack(SqStack* s){
     if(s!=NULL){
         free(s->Array);
         free(s);
     }
 }

 void  Push(ElemType x,SqStack* s){
     if(IsFull(*s)){
         s->Array=(ElemType *)realloc(s->Array,(s->Capacity+StackIncrement)*sizeof(ElemType));
     }
     if(!s->Array)
         Error("Full stack");
     else 
         s->Array[++s->Top] = x;

 }

 void Pop(SqStack* s){
     if(IsEmpty(s))
         Error("Empty stack");
     else
         s->Top--;
 }

 ElemType TopAndPop(SqStack* s){
     if(!IsEmpty(s))
         return s->Array[s->Top--];
     Error("Empty stack");
     return 0;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值