zoukankan      html  css  js  c++  java
  • c语言学习,模拟栈操作


    1.stack.c模拟栈操作函数的实现




    #include<stdio.h> #include<stdlib.h> static int sz=512; static char *stack;//数据栈 static int top=0;//栈指针 //用 static 修饰,作用延长变量生命周期,更重要一点防止其他文件对其值的修改 /* *初始化数据栈大小(申请动态内存记得释放掉) */ void init_stack(int size) { if(size==0) { size=sz; } else sz=size; stack=(char *)malloc(sz); } /* * *释放数据栈申请的内存空间 * */ void destory_stack(void) { free(stack); } /* *数据入栈时,如果内存不够,进行扩容 */ char push(char ch) { if(top==sz) { sz+=sz; stack=(char *)realloc(stack,sz);//扩容有两种情况,1内存空闲,直接扩容 //2数组后有数据,先拷贝元数据,然后进行扩容返回新的指针 } stack[top++]=ch; } /* *数据出栈 */ char pop(void) { return stack[--top]; } /* * *数据出栈完毕 */ int is_empty(void) { return top==0; } /* *数据入栈完毕 */ int is_full(void) { return top=sz; }

    2.stack.h 头文件的包含

    /*
    *对stack.c中的文件进行链接,申明
    */
    
    /*
    *初始化数据栈大小
    */
    extern void init_stack(int size);
    
    /*
    *销毁空间,防止内存泄漏
    */
    extern void destory_stack(void);
    
    /*
    *数据入栈,及扩容
    */
    extern char push(char ch);
    
    /*
    *数据出栈
    */
    extern char pop(void);
    
    extern int is_empty(void);
    
    
    extern int is_full(void);
    
    
    
    3.main.c效果演示

    #include<stdio.h>
    #include<stdlib.h>
    #include "stack.h";
    
    /*
    *模拟栈操作
    */
    
    int main(int argc,char **argv)
    {
        char str[20]="helloworld";
        char *p=str;
    
        /*while(1)
        {
            *p=getchar();
            if(*p++=='
    ')
            {
                printf("请输入*结束
    ");
                while(getchar()!='*')
                *p='*';
                p=str;
                break;
            }
        }*/
    
        init_stack(3);
    
        /*while(*p!='*')*/
        while(*p!='')
        {
            push(*p++);
        }
    
        printf("出栈结果:
    ");
    
        while(!is_empty())
        {
            putchar(pop());
        }
        destory_stack();
        system("pause");
        return 0;
    }
    
    
    
    4.结果演示
     picture
  • 相关阅读:
    多进程访问同一文件问题
    在主页面中实现Iframe中的子页面的切换
    在任务栏显示地理坐标
    ajax异步调用过程
    实现DIV标签的显示与隐藏
    使用supermap的心得
    nokia手机问题
    sys.webforms.pagerequestmanagerservererrorexception回发或回调参数无效
    AjaxScript地图打印[转]
    js获取下拉框中的值
  • 原文地址:https://www.cnblogs.com/paradisekiss/p/5118926.html
Copyright © 2011-2022 走看看