【数据结构】3.2共享栈(附代码实现)

在顺序栈的基础上,共享栈将一个连续的数组空间给两个栈共用,一定程度上解决了资源浪费的问题示意图如下!这里写图片描述


具体实现代码如下

#include<stdio.h>

#define MaxSize 5
#define ElemType int

typedef struct{
    ElemType data[MaxSize];
    int top_1,top_2;
}SqDoubleStack;

void init(SqDoubleStack &S);
bool is_empty_1(SqDoubleStack S);
bool is_empty_2(SqDoubleStack S);
bool is_full(SqDoubleStack S);
bool Push(SqDoubleStack & S, ElemType x, int stackNum);
bool Pop(SqDoubleStack &S, ElemType &x, int stackNum);
void Traverse(SqDoubleStack S,int stackNum);
bool Push(SqDoubleStack & S, ElemType x, int stackNum);

int main(void)
{
    int x;
    SqDoubleStack S;
    init(S);
    if(Push(S,1,1))
        printf("Push succeed!\n");
    Push(S,2,1);
    Push(S,2018,1);
    Traverse(S,1);
    if(Push(S,1,2))
        printf("Push succeed!\n");
    Push(S,2,2);
    Push(S,2019,2);
    Traverse(S,2);

    if(Pop(S,x,1))
    {
        printf("Pop succeed!\n");
        printf("The data popped out is %d!\n",x);
        Traverse(S,1);

    }
    if(Pop(S,x,2))
        {
            printf("Pop succeed!\n");
            printf("The data popped out is %d!\n",x);
            Traverse(S,2);
        }
}

void init(SqDoubleStack &S)
{
    S.top_1 = -1;
    S.top_2 = MaxSize;
}

bool is_empty_1(SqDoubleStack S)
{
    if(S.top_1 == -1)
        return true;
    else 
        return false;
}

bool is_empty_2(SqDoubleStack S)
{
    if(S.top_2 == MaxSize)
        return true;
    else
        return false;
}

bool is_full(SqDoubleStack S)
{
    if (S.top_1 + 1 == S.top_2)
        return true;
    else 
        return false;
}

bool Push(SqDoubleStack & S, ElemType x, int stackNum)
{
    if(is_full(S))
        return false;
    if(stackNum == 1)
    {
        S.data[++S.top_1] = x;
    }
    if(stackNum == 2)
    {
        S.data[--S.top_2] = x;
    }
    return true; 
}

bool Pop(SqDoubleStack &S, ElemType &x, int stackNum)
{
    if(stackNum == 1)
    {
        if(is_empty_1(S))
            return false;
        x = S.data[S.top_1--];
    }

    if(stackNum == 2)
    {
        if(is_empty_2(S))
            return false;
        x = S.data[S.top_2++];
    }
    return true;
}

void Traverse(SqDoubleStack S , int stackNum)
{
    if (stackNum == 1)
    {
        while(S.top_1 != -1)
            printf("%d\t",S.data[S.top_1--]);
    }
    else if (stackNum == 2)
    {
        while(S.top_2 != MaxSize)
            printf("%d\t",S.data[S.top_2++]);
    }
    printf("\n");
}

猜你喜欢

转载自blog.csdn.net/qq_39745474/article/details/81591175
今日推荐