顺序栈

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAXSIZE 50
typedef struct stack_Inilt
{
    int *base;
    int *top;
    int length;
} stack;
void initStack(stack *s)
{
    s->base = (int *)malloc(sizeof(int) * MAXSIZE);
    if (!s->base)
        exit(0);
    s->top = s->base;
    s->length = MAXSIZE;
}
int stackEmpty(stack *s)
{
    if (s->base == s->top)
        return 1;
    else
        return 0;
}
int stackLength(stack *s)
{
    return s->top - s->base;
}
int clearStack(stack *s)
{
    if (s->base)
    {
        s->top = s->base;
        return 1;
    }
}
int destroyStack(stack *s)
{
    if (s->base)
    {
        free(s->base);
        s->length = 0;
        s->base = s->top = NULL;
    }
    if (s->base == NULL)
    {
        return 1;
    }
}
void push(stack *s, int e)
{
    if (s->top - s->base == s->length && s->length != 0)
    {
        printf("stack  is  full\n");
        return;
    }
    else
    {
        *(s->top) = e;
        s->top++;
    }
}
int pop(stack *s, int *e)
{
    if (s->top - s->base == 0)
    {
        printf("stack  is  empty\n");
        return 0;
    }
    else
    {
        *e = *(--s->top);
    }
    return *e;
}
void printStack(stack *s)
{
    int *p;
    p = s->base;
    if (s->top - s->base == 0)
    {
        printf("stack  is  null\n");
        return;
    }
    else
    {
        while (p != s->top)
        {
            printf("%d->", *p);
            p++;
        }
        printf("\n");
    }
}
int main()
{
    stack s;
    initStack(&s);
    int e;
    printf("十次入栈:\n");
    for (int i = 0; i < 10; i++)
    {
        push(&s, i);
    }
    printStack(&s);
    printf("stack length:%d\n", stackLength(&s));
    printf("五次出栈\n");
    for (int i = 0; i < 5; i++)
    {
        pop(&s, &e);
    }
    printStack(&s);
    printf("stack length:%d\n", stackLength(&s));
    printf("压入一个元素\n");
    push(&s, 18);
    printStack(&s);
    printf("移出栈顶元素:\n");
    pop(&s, &e);
    printStack(&s);
    printf("销毁栈\n");
    destroyStack(&s);
    initStack(&s);
    printf("print  stack\n");
    printStack(&s);

    return 0;
}

 

 

posted @ 2022-05-12 19:10  error!!!!  阅读(22)  评论(0)    收藏  举报