简单的入栈出栈

简单的入栈和出栈操作。。。

#define MAXSIZE 26
typedef char ElemType;

typedef struct Stack
{
    ElemType *base;
    ElemType *top;
    int stackSize;
}Stack;

void stack_init(Stack *s);
void stack_des(Stack *s);
void stack_print(Stack *s);
void stack_pop(Stack *s, ElemType *e);
void stack_push(Stack *s, ElemType e);

int main()
{
    Stack s;
    int i = 0;
    char e;
    
    stack_init(&s);
    printf("初始化栈:\n");
    stack_print(&s);
    
    printf("输入1,pop;2,push;-1,结束:\n");
    scanf("%d", &i);
    while(i != -1)
    {
        getchar();
        switch(i)
        {
            case 1:
                stack_pop(&s, &e);
                printf("弹出:%c\n", e);
                break;
            case 2:
                printf("请输入要插入的值:");
                scanf("%c", &e);
                stack_push(&s, e);
                stack_print(&s);
                break;
        }
        scanf("%d", &i);
    }
    stack_print(&s); 
    stack_des(&s);
    return 0;
}

void stack_init(Stack *s)
{
    int i = 0;
    s->base = (ElemType *)malloc(sizeof(ElemType)*MAXSIZE);
    s->top = s->base;
    s->stackSize = MAXSIZE;
    
    for(i = 0; i<s->stackSize-1; i++)
    {
        *(s->top) = 'A' + i;
        s->top++;
    }
}

void stack_des(Stack *s)
{
    if(!s->base) {
        free(s->base);
    }
    s->base = NULL;
    s->top = NULL;
    s->stackSize = 0;
}

void stack_print(Stack *s)
{
    printf("\n");
    ElemType *p = s->top;
    while(s->top != s->base)
    {
        s->top--;
        printf("%c ", *(s->top));
    }
    printf("\n");
    s->top = p;
}

void stack_pop(Stack *s,  ElemType *e)
{
    if(s->base == s->top)
    {
        return;
    }
    s->top--;
    *e = *(s->top);
    
}

void stack_push(Stack *s, ElemType e)
{
    if(s->top-s->base >= s->stackSize)
    {
        return;
    }
    *(s->top) = e;
    s->top++;
}

 

posted @ 2017-08-14 15:55  牛奶无花果  阅读(230)  评论(0编辑  收藏  举报