zoukankan      html  css  js  c++  java
  • C语言实现栈

    1.单链表栈结构
      进入的元素是先进后出,类似一个停车库,最先停在最里面的车,最后才能出来。
        
      a.头文件 stacklisth.h
    C/C++ code
    /** ** 栈的链式结构 */ typedef struct NODE { struct NODE *link; char *name; }Node; /* ** 创建一个节点 ** */ Node* create_node(); /* ** 打印一个函数的节点所带信息 ** */ void printf_node(Node *head); /* ** 入栈 ** */ void push(char *name); /* ** 出栈 ** */ void pop(); /* ** 栈是否为空 ** */ int is_empty();


    b.具体实现 stacklist.c
    C/C++ code
    #include "stacklisth.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #define NAME_LENGTH 10 /* ** author:srgzyq ** email.srgzyq@gmail.com */ static Node *head; /* ** 创建一个节点实现 支持的name字符长度为10 ** */ Node* create_node() { Node *new = (Node *)malloc(sizeof(Node)); if(new == NULL) return NULL; // 开辟空间 char *name = (char *)calloc(NAME_LENGTH,sizeof(char)); if(!name) { free((Node *)new); return NULL; } new->name = name; return new; } void printf_node(Node *pNode) { printf("name: %s\n",pNode->name); } void push(char *name) { Node *new = create_node(); new->name = name; new->link = head; head = new; } void pop() { printf_node(head); Node *currNode = head; head = head->link; free(currNode); } int is_empty() { return head == NULL; }


      c.测试代码stacktest.c(注:用了兄弟伙的名字)
    C/C++ code
    #include <stdio.h> #include <stdlib.h> char data_arr[][10] = {"wangbo","roadie","niba","bobo","xingye"}; int main() { int len = 5; int index; for(index = 0; index < len; index++) push(data_arr[index]); while(!is_empty()) pop(); return EXIT_SUCCESS; }


    编译输出:
    gcc -o2 -o stacktest stacklist.c stacktest.c  
    ./stacktest  

    name: xingye

    name: bobo

    name: niba

    name: roadie

    name: wangbo

  • 相关阅读:
    串口调试助手
    自己动手编写俄罗斯方块
    ASP.NET Core log4net
    ASP.NET Core读取配置文件
    ASP.NETCore3 MVC
    ASP.NETCore2C#7.0新语法
    ASP.NETCore1C#6.0新语法
    C#加密解密
    前端通用的滚动条样式
    C# 106 短信发送
  • 原文地址:https://www.cnblogs.com/zzxap/p/2175654.html
Copyright © 2011-2022 走看看