網站首頁 編程語言 正文
堆棧的基本概念
堆棧是只能在一端增刪元素的表結構,該位置稱為棧頂堆棧的基本運算是壓入和彈出,前者相當于插入,而后者則是刪除最后插入的元素,形成后進先出的運算規則最后插入的元素在被彈出之前可以作為棧頂被外界訪問從空棧中彈出,或向滿棧中壓入,都被認為是一種錯誤
常見的棧有順序棧和鏈式棧
順序棧
鏈式棧
- 鏈式棧的C代碼實現
#include <stdio.h> #include <stdlib.h> /*節點的結構*/ typedef struct node { struct node* pnode; int data; }node_t; /*棧的結構*/ typedef struct stack { struct node* top;//棧頂指針 int size;//棧中數據個數 }stack_t; /*初始化棧*/ void stack_init(stack_t* stk) { stk->top = NULL; stk->size = 0; } /*壓棧操作*/ void stack_push(stack_t* stk, int data) { node_t *node = malloc(sizeof(node_t)); node->data = data; node->pnode = stk->top; stk->top = node; stk->size++; } /*彈棧:將棧中數據彈入buf*/ void stack_pop(stack_t* stk, int buf[], int size) { for(int i = 0; i < size; ++i) { if(stk->size == 0) { printf("棧中數據已彈凈!\n"); break; } node_t* temp = stk->top; buf[i] = stk->top->data; stk->top = stk->top->pnode; stk->size--; free(temp); } } /*刪除整個棧*/ void stack_deinit(stack_t* stk) { while(stk->size || stk->top) { node_t* temp = stk->top; stk->top = stk->top->pnode; stk->size--; free(temp); } } /*從棧頂自上而下打印棧中所有數據*/ void print_stack(stack_t* stk) { if(stk->size == 0) { printf("棧中無數據!\n"); } for(node_t* node = stk->top; node; node = node->pnode) { printf("%d ",node->data); } printf("\n"); } /*測試代碼*/ #define N 30 int main(void) { stack_t stack; int buf[N]; stack_init(&stack); printf("開始壓棧!\n"); for(int i = 0; i < N; ++i) { stack_push(&stack, i); } print_stack(&stack);//打印棧中數據 //stack_deinit(&stack); printf("開始彈棧!\n"); stack_pop(&stack, buf, N);//彈棧 print_stack(&stack); printf("取出的數據為:"); for(int i = 0; i < sizeof(buf) / sizeof(buf[0]); ++i) { printf("%d ", buf[i]); } printf("\n"); return 0; }
代碼運行效果
原文鏈接:https://blog.csdn.net/weixin_43361320/article/details/122030719
相關推薦
- 2023-03-16 redis如何取hash的值_Redis
- 2022-07-09 python沒有gpu,如何改用cpu跑代碼_python
- 2022-10-03 C++利用Opencv實現多個圓形檢測_C 語言
- 2022-07-06 C#中DataSet,DataTable,DataView的區別與用法_C#教程
- 2022-11-02 Pytest運行及其控制臺輸出信息_python
- 2023-08-15 .sync 父組件給子組件傳值 子組件修改父組件方法
- 2022-09-13 go開源項目用戶名密碼驗證的邏輯鬼才寫法_Golang
- 2023-08-16 uniapp頁面返回到上一個頁面,更新其數據
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支