注:此文章来自“CSDN”博主,仅在此借鉴,学习
各种基本算法实现小结(二)—— 堆 栈
(均已测试通过)
==============================================================
栈——数组实现
测试环境:Win - TC
- #include <stdio.h>
- char stack[512];
- int top=0;
- void push(char c)
- {
- stack[top]=c;
- top++;
- }
- char pop()
- {
- top--;
- return stack[top];
- }
- int is_empty()
- {
- return 0==top;
- }
- void main()
- {
- push('1');
- push('2');
- push('3');
- push('4');
- push('5');
- while(!is_empty())
- putchar(pop());
- putchar('/n');
- getch();
- }
运行结果:

====================================================
栈——数组实现2
测试环境:Win - TC
- #include <stdio.h>
- #include <malloc.h>
- /* typedef int DataType; */
- #define DataType int
- #define MAX 1024
- typedef struct
- {
- DataType data[MAX];
- int top;
- }stack, *pstack;
- pstack *init_stack()
- {
- pstack ps;
- ps=(pstack)malloc(sizeof(stack));
- if(!ps)
- {
- printf("Error. fail malloc.../n");
- return NULL;
- }
- ps->top=-1;
- return ps;
- }
- int empty_stack(pstack ps)
- {
- if(-1 == ps->top)
- return 1;
- else
- return 0;

本文详细介绍了使用数组、链表两种方式实现栈的算法,包括push、pop、is_empty等操作,并提供了相应的测试环境及结果。此外,还展示了链表实现的堆的插入、删除、显示等操作,帮助理解数据结构中的堆栈和队列原理。

1443

被折叠的 条评论
为什么被折叠?



