[PTA] 数据结构与算法题目集 6-7 在一个数组中实现两个堆栈

//如果堆栈已满,Push函数必须输出“Stack Full”并且返回false;如果某堆栈是空的,则Pop函数必须输出“Stack Tag Empty”(其中Tag是该堆栈的编号),并且返回ERROR。
Stack CreateStack(int MaxSize)
{
    Stack sta = (Stack)malloc(sizeof(struct SNode));
    sta->Data = (ElementType*)malloc(MaxSize*sizeof(ElementType));
    sta->Top1 = -1;
    sta->Top2 = MaxSize;
    sta->MaxSize = MaxSize;
    return sta;
}
bool Push(Stack S, ElementType X, int Tag)
{
    if (S == NULL)
        return false;
    if (S->Top1 + 1 == S->Top2)
    {
        printf("Stack Full\n");
        return false;
    }
    if (Tag == 1)
    {
        S->Data[++S->Top1] = X;
    }
    else
    {
        S->Data[--S->Top2] = X;
    }
    return true;
}
ElementType Pop(Stack S, int Tag)
{
    if (S == NULL)
        return ERROR;
    if (Tag == 1)
    {
        if (S->Top1 == -1)
        {
            printf("Stack %d Empty\n", Tag);
            return ERROR;
        }
        return S->Data[S->Top1--];
    }
    else
    {
        if (S->Top2 == S->MaxSize)
        {
            printf("Stack %d Empty\n", Tag);
            return ERROR;
        }
        return S->Data[S->Top2++];
    }
}
posted @ 2018-11-18 11:21  Ruohua3kou  阅读(441)  评论(0编辑  收藏  举报