当前位置: 首页 > news >正文

栈和队列的实现,咕咕咕

1.栈的实现

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int st;
typedef struct stack
{st* data;int top;int capacity;
}stack;
//检查扩容
void checkcapacity(stack* ps)
{if(ps->top==ps->capacity){int newcapacity=ps->capacity==0?4:ps->capacity*2;st* tmp=(st*)realloc(ps->data,newcapacity*sizeof(st));if(tmp==NULL){perror("tmp realloc");exit(1);}ps->data=tmp;ps->capacity=newcapacity;}
}
//初始化栈
void stackinit(stack* ps)
{ps->data=NULL;ps->top=ps->capacity=0;
}
//入栈
void stackpush(stack* ps,st x)
{assert(ps);checkcapacity(ps);ps->data[ps->top]=x;ps->top++;
}
//出栈
void stackpop(stack* ps)
{
assert(ps->top>0);
ps->top--;
}
//获取栈顶元素
st stacktop(stack* ps)
{assert(ps->top>0);return ps->data[ps->top-1];
}
//获取有效元素
int stacksize(stack* ps)
{return ps->top;
}
//判断是否为空
int stackempty(stack* ps)
{return ps->top==0;
}
//销毁栈
void stackdestroy(stack* ps)
{assert(ps->data);free(ps->data);ps->capacity=ps->top=0;
}

2.队列的实现

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int qt;
typedef struct qlistnode
{qt data;struct qlistnode* next;
}qnode;
typedef struct queue
{qnode* head;qnode* tail;int count;
}queue;
//初始化节点
qnode* buynode(qt x)
{qnode* newnode=(qnode*)malloc(sizeof(qnode));if(newnode==NULL){perror("newnode malloc");exit(1);}newnode->data=x;newnode->next=NULL;
}
//判断是否为空
int queueempty(queue* q)
{return q->head==NULL;
}
//初始化队列
void queueinit(queue* q)
{q->head=NULL;q->tail=NULL;q->count=0;
}
//队尾入队
void queuepush(queue* q,qt x)
{qnode* newnode=buynode(x);if(queueempty(q)){q->head=newnode;q->tail=newnode;}else{q->tail->next=newnode;q->tail=newnode;}q->count++;
}
//队头出队
void queuepop(queue* q)
{assert(!queueempty(q));qnode* tmp=q->head;q->head=q->head->next;if(q->head==NULL){q->tail==NULL;}free(tmp);q->count--;
}
//获取对头部元素
qt queuefront(queue* q)
{assert(!queueempty(q));return q->head->data;
}
//获取队尾元素
qt queueback(queue* q)
{assert(!queueempty(q));return q->tail->data;
}
//获取队列元素数量
int queuecount(queue* q)
{return q->count;
}
//销毁队列
void queuedestroy(queue* q)
{while(!queueempty(q)){queuepop(q);}
}

http://www.dtcms.com/a/284685.html

相关文章:

  • CTF之栅栏密码的传统型、W型与偏移量
  • ota之.加密算法,mcu加密方式
  • 开源 python 应用 开发(八)图片比对
  • Android wifi简单白名单实现逻辑
  • 20250717在荣品的PRO-RK3566开发板的Android13系统下解决点屏出现问题unsupport command data type: 217
  • 通俗的解释一下以太网中的端口号
  • 流式数据处理实战:用状态机 + scan 优雅过滤 AI 响应中的 `<think>` 标签
  • 深入理解CSS定位:绝对定位的包含块机制
  • 退休时间计算器,精准预测养老时间
  • 项目实战(18)-POE分离器
  • Spring底层原理(一)核心原理
  • RCU机制及常见锁的理解
  • 深入理解Java中的Map.Entry接口
  • 【数据结构】单链表的实现
  • python(one day)——春水碧于天,画船听雨眠。
  • Python 网络爬虫 —— requests 库和网页源代码
  • 网络爬虫的介绍
  • Kafka 配置参数详解:ZooKeeper 模式与 KRaft 模式对比
  • 【Android】Span的使用
  • 深入了解linux系统—— 信号的捕捉
  • 卷积神经网络--网络性能提升
  • 如何成为高级前端开发者:系统化成长路径。
  • 初识 二叉树
  • BI Agent vs. 传统BI工具:衡石科技视角下的效率与智能跃迁
  • 亚远景科技助力长城汽车,开启智能研发新征程
  • AI产品经理面试宝典第34天:破解人机社交关系面试题与答法
  • 一台显示器上如何快速切换两台电脑主机?
  • 【vue-2】Vue 3 中的 v-on 指令:全面指南与最佳实践
  • 无线调制的几种方式
  • .NET Framework版本信息获取(ASP.NET探针),获取系统的.NET Framework版本