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 函数及其实现,以便于更好地理解队列的初始化、插入和获取操作。

#include <stdio.h>
#include <stdlib.h>

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 *myroot, DataNode *myDataNode) {
    if (myroot->tail != NULL) {
        myroot->tail->next = myDataNode; // 将当前尾部的 next 指向新节点
    }
    myroot->tail = myDataNode; // 更新尾指针

    if (myroot->head == NULL) {
        myroot->head = myDataNode; // 如果队列为空,头指针也指向新节点
    }
}

// 从队列中获取数据节点
DataNode *queue_get(Que *myroot) { 
    DataNode *myDataNode = myroot->head; // 获取头节点
    
    if (myroot->head != NULL) {
        myroot->head = myroot->head->next; // 头指针后移
        myDataNode->next = NULL; // 断开与后续节点的联系

        if (myroot->head == NULL) {
            myroot->tail = NULL; // 如果队列为空,更新尾指针
        }
    }

    return myDataNode; // 返回被获取的节点
}

int main() {
    Que queue;
    queue_init(&queue); // 初始化队列

    // 创建一些数据节点并放入队列中(为了演示)
    for (int i = 0; i < 3; i++) {
        DataNode *new_node = (DataNode *)malloc(sizeof(DataNode)); // 动态分配内存
        
        new_node->data = "Sample data"; // 简单示例:使用相同字符串
        
        new_node->next = NULL;
        queue_put(&queue, new_node);
    }

    // 从队列中取出数据并打印
    for (int i = 0; i < 3; i++) {
        DataNode *node = queue_get(&queue);
        
        if (node != NULL) {
            printf("Got data: %s\n", node->data); // 打印取出的数据
            free(node); // 不要忘记释放内存
        } else {
            printf("Queue is empty!\n");
        }
    }

    return 0;
}

程序说明:

  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

注册

已经有帐号?