• C语言链式栈


    stack.h

    typedef struct Node_s {
    	int data;
    	struct Node_s *pNext;
    } Node_t, *pNode_t;
    
    typedef struct Stack_s {
    	pNode_t pHead;//栈顶指针,指向了链表的第一个结点
    	int size;//栈的元素个数
    } Stack_t, *pStack_t;
    
    void init(pStack_t pStack);
    void push(pStack_t pStack, int data);
    int isEmpty(pStack_t pStack);
    void pop(pStack_t pStack);
    int top(pStack_t pStack);
    int size(pStack_t pStack);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    main.c

    #define _CRT_SECURE_NO_WARNINGS
    #include 
    #include 
    #include 
    #include "stack.h"
    int main() {
    	Stack_t stack;
    	init(&stack);
    	for (int i = 0; i < 5; ++i) {
    		push(&stack, i);
    		printf("top = %d\n", top(&stack));
    	}
    	for (int i = 0; i < 6; ++i) {
    		pop(&stack);
    		printf("pop, top = %d\n", top(&stack));
    	}
    }
    //初始化
    void init(pStack_t pStack) {
    	memset(pStack, 0, sizeof(Stack_t));
    }
    //压栈
    void push(pStack_t pStack, int data) {
    	pNode_t pNew = (pNode_t)calloc(1, sizeof(Node_t));
    	pNew->data = data;
    	//这个链表只有pHead没有pTail,所以不用判断是否为空
    	pNew->pNext = pStack->pHead;
    	pStack->pHead = pNew;
    	++pStack->size;
    }
    //判空
    int isEmpty(pStack_t pStack) {
    	return pStack->size == 0;
    }
    //弹栈
    void pop(pStack_t pStack) {
    	if (isEmpty(pStack)) {
    		fprintf(stderr, "Stack is empty!\n");
    		return -1;
    	}
    	pNode_t pCur = pStack->pHead;
    	pStack->pHead = pCur->pNext;
    	free(pCur);
    	pCur = NULL;
    	--pStack->size;
    }
    //获取栈顶数据
    int top(pStack_t pStack) {
    	if (isEmpty(pStack)) {
    		fprintf(stderr, "Stack is empty!\n");
    		return -1;
    	}
    	return pStack->pHead->data;
    }
    //获取栈的大小
    int size(pStack_t pStack) {
    	return pStack->size;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
  • 相关阅读:
    with recursive用法
    无代码开发重新指派负责人入门教程
    在 Vue3 项目中如何关闭 ESLint
    如何确定自己的armbian系统是不是ARM64架构
    vgg16猫狗识别
    NodeJS解析Error中stack堆栈信息
    基于C语言实现的PA4实验报告
    pod&node选择部署策略: nodeSelector和nodeAffinity
    干货 | Dubbo 接口测试原理及多种方法实践总结
    Spring-依赖注入补充
  • 原文地址:https://blog.csdn.net/weixin_44722009/article/details/134497712