使用数组实现栈(C语言)

栈结构体定义

#define StackSize 100
typedef int DataType; 
typedef struct{
    DataType stack[StackSize];
    // 用于指向栈顶元素
    int top;
}SeqStack;

算法实现

// 初始化栈
void InitStack(SeqStack *S){
     S->top = 0;
}
// 判断栈是否为空
int StackEmpty(SeqStack S){
     if(S.top == 0){
          return 1;
     }else{
          return 0;
     }                    
}
// 取栈顶元素
int GetTop(SeqStack S,DataType *e){
     if(S.top<=0){
          printf("当前栈已空\n");
          return 0; 
     }           
     *e = S.stack[S.top - 1]; 
     return 1;    
}
// 将元素e入栈
int PushStack(SeqStack *S,DataType e){
     if(S->top >= StackSize){
          printf("当前栈已满,新的元素不能进栈\n");
          return 0;
     }   
     S->stack[S->top] = e; 
     S->top++;    
     return 1;           
}
// 将栈顶元素出栈,并赋值给e
int PopStack(SeqStack *S,DataType *e){
     if(S->top==0){
          printf("当前栈已空,不能出栈\n");
          return 0; 
     }
     S->top--;
     *e = S->stack[S->top];    
     return 1;                            
}
// 栈的长度
int StackLength(SeqStack S){
     return S.top;
}
// 清空栈
ClearStack(SeqStack *S){
     S->top = 0;                    
}

你可能感兴趣的:(使用数组实现栈(C语言))