栈实现 C语言
2024-09-04 14:15:05
最近上来写了一下栈,理解数据结构的栈。
头文件:stack.h
初始化栈结构与函数定义:
#include<stdlib.h>
#include <stdio.h>
#include<memory.h>
#define N 100 struct stack
{
int data[N];
int top;//标识栈顶
}; typedef struct stack Stack;//Stack别名 void init(Stack * p);//初始化
int isempty(Stack * p);//判定栈是否空
int isfull(Stack * p);//判定栈溢出
int gettop(Stack * p);//获取栈顶
void push(Stack * p, int key);//插入数据
void pop(Stack * p);//吐出
void show(Stack * p);//显示栈
stack.c
实现函数:初始化,判断栈顶,溢出等
#include "stack.h" void init(Stack * p)//初始化
{
p->top = -;//代表为空
memset(p->data, , sizeof(int)*N);//数据清零 }
int isempty(Stack * p)//判定栈是否空
{
if (p->top==-)
{
return ;//1为空
}
else
{
return ;//0不为空
}
}
int isfull(Stack * p)//判定栈溢出
{
if (p->top==N-)
{
return ;///溢出
}
else
{
return ;//还能再喝点
}
}
int gettop(Stack * p)//获取栈顶
{
return p->data[p->top];//获取栈顶
}
void push(Stack * p, int key)//插入数据
{
if (isfull(p)==)
{
return;
}
else
{
p->top += ;
p->data[p->top] = key;//压入数据
}
}
void pop(Stack * p)//吐出
{
if (isempty(p)==)
{
return;
}
else
{
p->top -= ;//出栈
}
} void show(Stack * p)
{
int i;
if (isempty(p) == )
{
return;
}
else
{
printf("\n栈的数据是\n");
for (i = ; i <= p->top;i++)
{
printf("%4d", p->data[i]);//打印栈的数据
} printf("\n");
}
}
主函数main.c
#include<stdio.h>
#include"stack.h"
void main()
{
int i = ;
int a[] = { , , , , , , , , , }; Stack mystack;
init(&mystack);//初始化
for (i = ; i < ;i++)
{
push(&mystack, i);
}
//全部装完再吐
while (!isempty(&mystack))
{
printf("%d", gettop(&mystack)); //获取栈顶
pop(&mystack); //吐出
} printf("\n"); //装一个吐一个。。。。。
init(&mystack);//初始化
for (i = ; i < ; i++)
{
push(&mystack, i);
printf("%d", gettop(&mystack));
pop(&mystack);
}
getchar();
}
最新文章
- P2特征(一)
- Call requires API level 21(Current min is 16)
- 前端html、Javascript、CSS技术小结
- .Net中的并行编程-6.常用优化策略
- jQuery(function($){...})与(function($){...})(jQuery)知识点分享
- MEF学习笔记
- 如何改变word修订模型下的视图
- oralce dubugs
- jQuery+Ajax+Jsp做二级级联
- magento模块的建立
- Android 5.1.1在外置SD卡中创建文件夹
- Lucene入门-安装和运行Demo程序
- Python 学习之路2
- echarts异步数据加载(在下拉框选择事件中异步更新数据)
- Nginx的负载均衡 - 加权轮询 (Weighted Round Robin) 下篇
- winform devexpress 用法汇总
- 小程序获取当前页面URL
- linux基础之用户和组管理及权限
- WPF 异步刷新页面,创建定时器
- 全网最详细的PLSQL Developer + Oracle client的客户端 或者 PLSQL Developer + Oracle server服务端的下载与安装过程(图文详解)
热门文章
- delphi 组件容器TObjectList代替List
- tr th td
- Fundamentals of Garbage Collection
- react-navigation 3.x版本的使用
- tomcat限制ip访问
- Spring Boot gradle 集成servlet/jsp 教程及示例
- jquery获得/修改html标签
- Sensitivity, specificity, and reproducibility of RNA-Seq differential expression calls RNA-Seq差异表达调用的灵敏度 特异性 重复性
- scala 排序
- smarty foreach