开发类twoStacks,它用一个数组描述两个栈。一个栈的栈底在位置0,另一个栈的栈底在位置arrayLength-1。

课后练习:开发类twoStacks,它用一个数组描述两个栈。一个栈的栈底在位置0,另一个栈的栈底在位置 arrayLength-1。两个栈都向数组的中间增长(见图8-4)。该类的方法必须能够在每一个栈中实施ADT栈的所有操作。而且每一个方法的复杂度应为O(1),其中不包括改变数组大小所需要的时间。

img


#define MAXSIZE 100
class twoStack{
    private: int nums[MAXSIZE]{};
    private: int firstTop=0,secondTop=MAXSIZE;

    bool push_first(int data){
        if(firstTop==secondTop){
            printf("FULL!\n");
            return false;
        }
        nums[firstTop++] = data;
        return true;
    }
    bool push_second(int data){
        if(firstTop==secondTop){
            printf("FULL!\n");
            return false;
        }
        nums[--secondTop] = data;
        return true;
    }

    int first_Top(){
        if(firstTop==0){
            printf("firstStack is empty!\n");
            return -1;
        }
        return nums[firstTop-1];
    }

    int second_Top(){
        if(secondTop==MAXSIZE){
            printf("secondStack is empty!\n");
            return -1;
        }
        return nums[secondTop];
    }

    void first_Pop(){
        if(firstTop==0){
            printf("firstStack is empty!\n");
        }else{
            firstTop--;
        }
    }

    void second_Pop(){
        if(secondTop==MAXSIZE){
            printf("secondStack is empty!\n");
        }else{
            secondTop++;
        }
    }

    bool firstStack_Empty(){
        return firstTop == 0;
    }

    bool secondStack_Empty(){
        return secondTop == MAXSIZE;
    }
    
    
};

Stack CreateStack( int MaxElements )
{
    Stack S = (struct StackRecord *)malloc(sizeof(struct StackRecord));
    S->Array = (ElementType *)malloc(sizeof(ElementType)*MaxElements);//注意数组申请的大小
    S->Capacity = MaxElements;
    S->Top1 = -1;
    S->Top2 = MaxElements;
    return S;
}
int IsEmpty( Stack S, int Stacknum )
{
    if(Stacknum == 1&&S->Top1==-1)
    {
        return 1;
    }
    if(Stacknum == 2&&S->Top2==S->Capacity)
    {
        return 1;
    }
     return 0;
}
int IsFull( Stack S )
{
    if(S->Top1+1==S->Top2)  return 1;
    return 0;
}
int Push( ElementType X, Stack S, int Stacknum )
{
    if(IsFull(S))   return 0;
    else{
        if(Stacknum == 1)
        {
            S->Array[++S->Top1] = X;
        }
        else
        {
            S->Array[--S->Top2] = X;
        }
        return 1;
    }
}
ElementType Top_Pop( Stack S, int Stacknum )
{
    if(IsEmpty(S,Stacknum))  return ERROR;
    if(Stacknum == 1)  return S->Array[S->Top1--];//返回栈顶元素后并更新栈顶
    else return S->Array[S->Top2++];
}