zoukankan      html  css  js  c++  java
  • 简单的入栈出栈

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

    #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("初始化栈:
    ");
        stack_print(&s);
        
        printf("输入1,pop;2,push;-1,结束:
    ");
        scanf("%d", &i);
        while(i != -1)
        {
            getchar();
            switch(i)
            {
                case 1:
                    stack_pop(&s, &e);
                    printf("弹出:%c
    ", 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("
    ");
        ElemType *p = s->top;
        while(s->top != s->base)
        {
            s->top--;
            printf("%c ", *(s->top));
        }
        printf("
    ");
        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++;
    }
  • 相关阅读:
    Java中常见的异常
    WebView中Js与Android本地函数的相互调用
    Gson解析POJO类中的泛型参数
    JAVA反射技术的使用
    Couchbase 找回登录密码
    微信内网页支付开发手记
    Android实现自定义字体
    Android实现图片裁切
    Android实现ExpandableTextView可扩展TextView
    仿美团实现地域选择(二)
  • 原文地址:https://www.cnblogs.com/buerr/p/7358308.html
Copyright © 2011-2022 走看看