C语言共享栈的各种操作

#include 
#include 

#define MAXSIZE 10
#define LEN sizeof(SqDoubleStack)

typedef struct 
{
    int data[MAXSIZE];
    int top1;
    int top2;
}SqDoubleStack;

SqDoubleStack *S;

void InitStack()
{
    S = (SqDoubleStack*)malloc(LEN);
    S -> top1 = -1;
    S -> top2 = MAXSIZE;
}

int Push()
{
    int e,i;
    if(S -> top1 + 1 == S -> top2)
    {
        printf("stack full!\n");
        return 0;
    }
    printf("Please input value:");
    scanf("%d",&e);
    printf("Please input stack num:");
    scanf("%d",&i);
    if(i == 1)
    {
        S -> data[++S -> top1] = e;
    }
    else if(i == 2)
    {
        S -> data[--S -> top2] = e;
    }
    return 1;
}

int Pop()
{
    int i;
    printf("Please input stack num:");
    scanf("%d",&i);
    if(i == 1)
    {
        if(S -> top1 == -1)
        {
            printf("stack null!\n");
            return 0;
        }
        S -> top1--;
    }
    else if(i == 2)
    {
        if(S -> top2 == MAXSIZE)
        {
            printf("stack null!\n");
            return 0;
        }
        S -> top2++;
    }
    return 1;
}

void ClearStack()
{
    S -> top1 = -1;
    S -> top2 = MAXSIZE;
}

void DestroyStack()
{
    S -> top1 = -1;
    S -> top2 = MAXSIZE;
    free(S);
    S = NULL;
}

void EmptyStack()
{
    if(S -> top1 == -1 && S -> top2 == MAXSIZE)
    {
        printf("stack empty!\n");
    }
    else
    {
        printf("stack not empty!\n");
    }
}

void LengthStack()
{
    printf("length = %d\n",S -> top1 + 1 + MAXSIZE - S -> top2);
}

int GetTop()
{
    int i;
    printf("Please input stack num:");
    scanf("%d",&i);
    if(i == 1)
    {
        if(S -> top1 == -1)
        {
            printf("get top error!\n");
            return 0;
        }
        printf("data = %d\n",S -> data[S -> top1]);
    }
    else if(i == 2)
    {
        if(S -> top2 == MAXSIZE)
        {
            printf("get top error!\n");
            return 0;
        }
        printf("data = %d\n",S -> data[S -> top2]);
    }
    return 1;
}

void TraverseStack()
{
    int i = 0;
    while(i <= S -> top1)
    {
        printf("data = %d\n",S -> data[i++]);
    }
    i = S -> top2;
    while(i < MAXSIZE)
    {
        printf("data = %d\n",S -> data[i++]);
    }
}

int main()
{
    int n;
    while(1)
    {
        printf("1.Init 2.Push 3.Pop 4.Clear 5.Destroy 6.Empty\n 7.Length 8.GetTop 9.Print 10.Exit\n");
        printf("Please input num:");
        scanf("%d",&n);
        switch(n)
        {
            case 1:InitStack();break;
            case 2:Push();break;
            case 3:Pop();break;
            case 4:ClearStack();break;
            case 5:DestroyStack();break;
            case 6:EmptyStack();break;
            case 7:LengthStack();break;
            case 8:GetTop();break;
            case 9:TraverseStack();break;
        }
        if(n == 10)
            break;
    }

}

你可能感兴趣的:(C语言,C语言的学习历程,C语言,共享栈)