49 阅读1分钟

栈的含义:限制仅在表的一端进行插入和删除运算的线性表。
插入、删除的一端为栈顶(Top),另一端为栈底。当表中没有元素时称为空栈。栈为后进先出(Last In First Out)的线性表,简称为LIFO表。
栈的基本运算

Status InitStack(SqStack *S) /* 创建栈*/
{
    int i,n;
    ElemType e;
    S->base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
    if(!S->base)
    exit(OVERFLOW);
    S->top=s->base;
    S->stacksize=STACK_INIT_SIZE;
    printf("请输入栈内的数据个数:")
    scanf("%d",&n);
    if(n>=S->stacksize)
    {
        S->base=(ElemType *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(ElemType));
        if(!S->base)
        exit(OVERFLOW);
        S->top=S->base+S->stacksize;
        S->stacksize+=STACKINCREMENT;
        }
        *S->top++=e;
    }

}
Status GetTop(SqStack *S,ElemType e) /*取栈顶元素并用e返回 */
{
    if(S->top==S->base)
        return 0;
    e=*(S->top-1);
    return e;
}
Status Push(SqStack *S,ElemType e)    /*插入e为栈顶元素
{
    if(S->top-S->base>=S->stacksize)
    {
    S->base=(ElemType *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(Elemtype));
    if(!S->base)
    {
    exit(OVERFLOW);
    S->top=S->base+S->stacksize;
    S->stacksize+=STACKINCREMENT;
    }
    *S->top++=e;
    }
    }
}
Status Pop(SqStack *S,ElemType *e)  /*删除栈顶元素并用e返回 */
{
    if(S->top==S->base)
        return 0;
    *e=*S->top;
    return *e;
}
Status StackEmpty(SqStack S)    /*判断栈是否为空*/
{
    if(S->base==S->top)
         return 1;
    else 
         return 0;
}
Status StackLength(SqStack S)      /*求栈的长度*/
{
    int i=0;
    while(S->top>S->base)
     {
         S->base++;
         i++;
     }
     return i;
}
Status Nizhi(SqStack S)                        /*将栈中元素逆置*/
{
    SqStack A,B;
    ElemType e;
    if(Init(&A)==OVERFLOW)
        printf("构造失败,退出程序!\n");
    if(Init(&B)==OVERFLOW)
        printf("构造失败,退出程序!\n");
    while(!StackEmpty(S))
    {
        Pop(&S,&e);
        PushSq(&A,e);
    }
    while(!StackEmpty(A))
    {
        Pop(&A,&e);
        PushSq(&B,e);
    }
    printf("逆置后\n");
    while(!StackEmpty(B))
    {
        Pop(&B,&e);
        printf("%d\n",e);
        PushSq(&S,e);
    }
    return OK;
}