数据结构 - 自写链式队列
发布日期:2021-07-01 00:18:48 浏览次数:2 分类:技术文章

本文共 1591 字,大约阅读时间需要 5 分钟。

数据结构学了有一阵子了,就自己模仿C++自带的队列写了一个链队,用法和C++的差不多,不足之处请指教。

#include 
#include
typedef int QElemType;//数据类型 typedef struct QNode { QElemType data; struct QNode *next;}*QueuePtr;QueuePtr p;struct LinkQueue { int length;//队列长度 QueuePtr head, tail;//头尾指针 LinkQueue() {//初始化 length = 0; head = tail = (QNode *)malloc(sizeof(QNode)); head -> next = NULL; } void push(QElemType e) {//入队 length++; p = (QNode*)malloc(sizeof(QNode)); p -> data = e; p -> next = NULL; tail -> next = p; tail = p; } void pop() {//出队 if (head != tail) { length--; p = head -> next; head -> next = p -> next; if (tail == p) tail = head; free(p); } } bool empty() {//判断队列是否为空 return !length; } void clear() {//清空队列 length = 0; while (head != tail) { p = head -> next; head -> next = p -> next; if (tail == p) tail = head; free(p); } } QElemType front() {//访问队首元素 if (head != tail) return head -> next -> data; } QElemType back() {//访问队尾元素 if (head != tail) return tail -> data; } int size() {//返回队列长度 return length; }};int main() { LinkQueue Q; Q.push(3); Q.push(2); Q.push(5); Q.push(6); Q.push(9); printf("队列的长度:%d\n", Q.size()); printf("队列中的元素:"); while (!Q.empty()) { printf("%d ", Q.front()); Q.pop(); } return 0; }

转载地址:https://lzyws739307453.blog.csdn.net/article/details/91653271 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:AcWing — IncDec序列(差分+贪心)
下一篇:洛谷 — 旅行商的背包(背包)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月25日 05时33分49秒