ZBLOG

参考程序 2: #include typedef struct DataNode{ char *data; struct DataNode *next; } DataNode; typedef struct{ DataNode *head, *tail; } Que; void queue_init(Que *myroot) { myroot->head=NULL; myroot->tail=NULL; } void queue_put(Que *myro...

在您提供的代码中,有一些问题需要修正和补充。下面是修订后的完整代码,其中包括 main 函数及其实现,以便于更好地理解队列的初始化、插入和获取操作。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct DataNode {
  4. char *data;
  5. struct DataNode *next;
  6. } DataNode;
  7. typedef struct {
  8. DataNode *head, *tail;
  9. } Que;
  10. // 初始化队列
  11. void queue_init(Que *myroot) {
  12. myroot->head = NULL;
  13. myroot->tail = NULL;
  14. }
  15. // 向队列添加数据节点
  16. void queue_put(Que *myroot, DataNode *myDataNode) {
  17. if (myroot->tail != NULL) {
  18. myroot->tail->next = myDataNode; // 将当前尾部的 next 指向新节点
  19. }
  20. myroot->tail = myDataNode; // 更新尾指针
  21. if (myroot->head == NULL) {
  22. myroot->head = myDataNode; // 如果队列为空,头指针也指向新节点
  23. }
  24. }
  25. // 从队列中获取数据节点
  26. DataNode *queue_get(Que *myroot) {
  27. DataNode *myDataNode = myroot->head; // 获取头节点
  28. if (myroot->head != NULL) {
  29. myroot->head = myroot->head->next; // 头指针后移
  30. myDataNode->next = NULL; // 断开与后续节点的联系
  31. if (myroot->head == NULL) {
  32. myroot->tail = NULL; // 如果队列为空,更新尾指针
  33. }
  34. }
  35. return myDataNode; // 返回被获取的节点
  36. }
  37. int main() {
  38. Que queue;
  39. queue_init(&queue); // 初始化队列
  40. // 创建一些数据节点并放入队列中(为了演示)
  41. for (int i = 0; i < 3; i++) {
  42. DataNode *new_node = (DataNode *)malloc(sizeof(DataNode)); // 动态分配内存
  43. new_node->data = "Sample data"; // 简单示例:使用相同字符串
  44. new_node->next = NULL;
  45. queue_put(&queue, new_node);
  46. }
  47. // 从队列中取出数据并打印
  48. for (int i = 0; i < 3; i++) {
  49. DataNode *node = queue_get(&queue);
  50. if (node != NULL) {
  51. printf("Got data: %s\n", node->data); // 打印取出的数据
  52. free(node); // 不要忘记释放内存
  53. } else {
  54. printf("Queue is empty!\n");
  55. }
  56. }
  57. return 0;
  58. }

程序说明:

  1. 结构体定义

    • DataNode 定义了一个数据节点,包含一个字符串 data 和指向下一个节点的指针。
    • Que 是一个表示队列的结构体,包含头指针和尾指针。
  2. 函数实现

    • queue_init():初始化队列,将头和尾都设为 NULL
    • queue_put():将新的数据节点添加到队列末尾。
    • queue_get():从队列头部移除并返回一个数据节点。
  3. 主函数 (main):

    • 初始化一个空的队列。
    • 创建多个数据节点并将它们放入队列。
    • 从队列中获取并打印这些数据,并释放分配给每个数据节点的内存。

请根据需要调整程序逻辑或扩展功能。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=19171

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?