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

    #include <stdio.h>
    #include <stdbool.h>
    #include <stdlib.h>
    
    typedef struct node
    {
        int data;
        struct node* next;
    }Node;
    
    typedef struct line_stack 
    {
        Node* top;
        int len;
    }Stack;
    
    Stack* creat_stack()
    {
        Stack* line = (Stack*)malloc(sizeof(Stack));
        line->top = NULL;
        line->len = 0;
        return line;
    }
    
    Node* creat_node(int data)
    {
        Node* node = (Node*)malloc(sizeof(Node));
        node->data = data;
        node->next = NULL;
        return node;
    }
    
    bool empty_stack(Stack* sta)
    {
        return !sta->len;
    }
    
    void push_stack(Stack* sta, int data)
    {
        Node* node = creat_node(data);
        if (empty_stack(sta)) {
            sta->top = node;
        } else {
            node->next = sta->top;
            sta->top = node;
        }
        sta->len++;
    }
    
    Node* top_stack(Stack* sta)
    {
        if (empty_stack(sta))
            return NULL;
        return sta->top;
    }
    
    bool pop_stack(Stack* sta)
    {
        if (empty_stack(sta))
        {
            return false;
        }
        Node* node = sta->top;
        sta->top = node->next;
        printf("pop_stack:%d
    ",node->data);
        free(node);
        sta->len--;
        return true;
    }
    
    void destory_stack(Stack* sta)
    {
        while (pop_stack(sta))
        {
            ;
        }
        free(sta);
    }
    
    int main()
    {
        int i;
        Stack* sta = creat_stack();
        for (i = 1; i <= 5; i++) {
            push_stack(sta, i);
            printf("%d
    ", top_stack(sta)->data);
        }
        destory_stack(sta);
        return 0;
    }
  • 相关阅读:
    06 继承与多态
    动手动脑 4 String 类
    字串加密
    课后作业(查询类对象创建个数)
    动手动脑 3 类与对象
    动手动脑 (第二次)
    IOS 网络判断
    ios常用的几个动画代码
    iOS Get方式带中文不能请求网络
    UILabel Text 加下划线
  • 原文地址:https://www.cnblogs.com/zgen1/p/14585428.html
Copyright © 2011-2022 走看看