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 语句等。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. typedef struct DataNode {
  5. char *data;
  6. struct DataNode *next;
  7. } DataNode;
  8. typedef struct {
  9. DataNode *head;
  10. DataNode *tail;
  11. } Que;
  12. // 初始化队列
  13. void queue_init(Que *myroot) {
  14. myroot->head = NULL;
  15. myroot->tail = NULL;
  16. }
  17. // 将节点放入队列
  18. void queue_put(Que *myroot, DataNode *myDataNode) {
  19. if (myroot->tail != NULL) {
  20. myroot->tail->next = myDataNode; // 连接新节点
  21. }
  22. myroot->tail = myDataNode; // 更新尾指针
  23. if (myroot->head == NULL) {
  24. myroot->head = myDataNode; // 如果头为空,设置为新节点
  25. }
  26. }
  27. // 从队列中获取节点
  28. DataNode* queue_get(Que *myroot) {
  29. DataNode *myDataNode = myroot->head;
  30. if (myDataNode != NULL) {
  31. myroot->head = myroot->head->next; // 更新头指针
  32. myDataNode->next = NULL; // 清空被取出节点的下一个指针
  33. if (myroot->head == NULL) {
  34. myroot->tail = NULL; // 如果头变为空,则更新尾指针
  35. }
  36. }
  37. return myDataNode; // 返回被取出的节点
  38. }
  39. int main() {
  40. Que *myroot;
  41. DataNode *tmpNode;
  42. char str[1024];
  43. int ts, qs, i;
  44. qs = sizeof(Que);
  45. ts = sizeof(DataNode);
  46. printf("sizeof(Que): %d, sizeof(DataNode): %d\n", qs, ts);
  47. myroot = (Que *)malloc(qs); // 分配内存给队列
  48. queue_init(myroot); // 初始化队列
  49. // 输入4个字符串并将其放入队列中
  50. for (i = 0; i < 4; i++) {
  51. scanf("%s", str);
  52. tmpNode = (DataNode *)malloc(ts); // 分配内存给数据节点
  53. tmpNode->data = (char *)malloc(strlen(str) + 1);
  54. strcpy(tmpNode->data, str);
  55. tmpNode->next = NULL;
  56. queue_put(myroot, tmpNode); // 将数据节点放入队列中
  57. printf("queue_put a node , used: %d\n", strlen(str) + 1 + ts);
  58. }
  59. while (myroot->tail != NULL) {
  60. tmpNode = queue_get(myroot); // 从队列中获取数据节点
  61. printf("queue_get a node: %s, freed: %d\n", tmpNode->data,
  62. strlen(tmpNode->data) + 1 + ts);
  63. free(tmpNode->data);
  64. free(tmpNode); // 释放内存
  65. }
  66. free(myroot); // 最后释放整个队列的内存
  67. return 0; // 返回成功退出程序
  68. }

改进与说明:

  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

注册

已经有帐号?