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

原文链接: https://www.cnblogs.com/zzxap/archive/2011/06/30/2175654.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/27905

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午5:29
下一篇 2023年2月8日 上午5:29

相关推荐