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++;
    }
  • 相关阅读:
    cocos2d学习笔录1
    js 动态切换视频
    Android之一个简单计算器源代码
    git-daemon的快捷搭建
    题目1384:二维数组中的查找
    [cocos2d-x]HelloWorldDemo
    ios开发者创建app应用开发授权文件 实战方法:
    一些小工具方法,能将容器转换成指定的数组类型有使用泛型
    Mockito文档-单元测试技术
    【UNIX网络编程】FIFO
  • 原文地址:https://www.cnblogs.com/buerr/p/7358308.html
Copyright © 2011-2022 走看看