ZBLOG

帮我规范化:#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 *myroot...

下面是您提供的代码的规范化版本。我对代码进行了格式化和注释,以提高可读性和维护性。特别注意了缩进、空格、以及一些小的改进,如添加 #include <stdlib.h>return 语句等。

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

typedef struct DataNode {
    char *data;
    struct DataNode *next;
} DataNode;

typedef struct {
    DataNode *head;
    DataNode *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; // 连接新节点
    }
    myroot->tail = myDataNode; // 更新尾指针

    if (myroot->head == NULL) { 
        myroot->head = myDataNode; // 如果头为空,设置为新节点
    }
}

// 从队列中获取节点
DataNode* queue_get(Que *myroot) {
    DataNode *myDataNode = myroot->head;

    if (myDataNode != NULL) {
        myroot->head = myroot->head->next; // 更新头指针
        myDataNode->next = NULL; // 清空被取出节点的下一个指针
        
        if (myroot->head == NULL) {
            myroot->tail = NULL; // 如果头变为空,则更新尾指针
        }
    }

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

int main() {
    Que *myroot;
    DataNode *tmpNode;
    char str[1024];
    
    int ts, qs, i;

    qs = sizeof(Que);
    ts = sizeof(DataNode);
    
    printf("sizeof(Que): %d, sizeof(DataNode): %d\n", qs, ts);

    myroot = (Que *)malloc(qs); // 分配内存给队列
    queue_init(myroot); // 初始化队列

   // 输入4个字符串并将其放入队列中
   for (i = 0; i < 4; i++) {
       scanf("%s", str);
       tmpNode = (DataNode *)malloc(ts); // 分配内存给数据节点
      
       tmpNode->data = (char *)malloc(strlen(str) + 1); 
       strcpy(tmpNode->data, str);
       tmpNode->next = NULL;

       queue_put(myroot, tmpNode); // 将数据节点放入队列中
       printf("queue_put a node , used: %d\n", strlen(str) + 1 + ts);
   }

   while (myroot->tail != NULL) { 
       tmpNode = queue_get(myroot); // 从队列中获取数据节点

       printf("queue_get a node: %s, freed: %d\n", tmpNode->data,
              strlen(tmpNode->data) + 1 + ts);

       free(tmpNode->data); 
       free(tmpNode); // 释放内存
   }

   free(myroot); // 最后释放整个队列的内存

   return 0; // 返回成功退出程序
}

改进与说明:

  1. 代码格式:添加了适当的缩进和空行以提高可读性。
  2. 包括必要的头文件:添加了 #include <stdlib.h> 用于动态内存分配函数。
  3. 返回类型:在 main 函数前加上了 int 类型,并在最后增加了 return 0; 来表示程序正常结束。
  4. 注释:在关键部分加入了注释,帮助理解每段代码的作用。

请根据自己的需求进一步调整或优化这段代码!


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?