博客
关于我
链队列——出入队列
阅读量:297 次
发布时间:2019-03-03

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

队列数据结构实现

队列是一种先进先出的数据结构,可以通过两端操作数据。在本次实现中,我们使用两个结构体分别存储队列的头和尾节点。

结构体定义如下:

```cstruct node { int data; node *next; };

struct Queue

{
node *head; // 表头指针
node *rear; // 尾部指针
};

Queue Q; // 队列对象

初始化队列时,默认将头节点和尾节点初始化为一个空节点:

```cQ.head = new node; Q.rear = new node; Q.head->next = NULL; Q.rear->next = NULL;

实现队列的增操作(get_link函数):

```cvoid get_link(int x, Queue *Q) { node *tail = Q.rear; // 获取当前尾部节点
while (x--)  {      node *q = new node;      scanf("%d", &q->data);      tail->next = q;      q->next = NULL;      tail = q;  }  Q.rear = tail;  // 更新尾部指针

实现队列的删操作(out_link函数):

```cvoid out_link(node *head) { node *q = head->next; while (q) { printf("%d\n", q->data); q = q->next; } head->next = q; // 将原头节点的下一个指针设为空节点

主函数实现:

```cint main() { int x; scanf("%d", &x);
node *head = new node;  Q.head = Q.rear = head;  // 初始化头和尾都指向同一个空节点  get_link(x, &Q);  // 读取并添加x个节点  out_link(Q.head);  // 输出队列中的数据  if (!Q.head->next)  {      printf("队列为空\n");  }  return 0;

}

整个实现通过动态分配节点实现了队列的基本操作,支持插入和删除数据。通过尾部指针的更新确保了队列的高效操作。

转载地址:http://oqsl.baihongyu.com/

你可能感兴趣的文章
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>
Node-RED中使用node-random节点来实现随机数在折线图中显示
查看>>
Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
查看>>
Node-RED中使用Notification元件显示警告讯息框(温度过高提示)
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
Node.js 函数是什么样的?
查看>>
Node.js 历史
查看>>
Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
node.js 简易聊天室
查看>>