建立一个包含若干整数(比如1,2,3,4,5)的单向链表,然后通过某些算法,将其中的数据翻转(比如5,4,3,2,1)

柔情只为你懂 2023-07-06 10:26 9阅读 0赞

更多资料请点击:我的目录
本篇仅用于记录自己所学知识及应用,代码仍可优化,仅供参考,如果发现有错误的地方,尽管留言于我,谢谢!

运行结果:
在这里插入图片描述

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node//设计节点
  4. {
  5. int data;
  6. struct node *next;
  7. };
  8. struct node *list()//初始化一个带头节点的空链表
  9. {
  10. struct node *head = malloc(sizeof(struct node));
  11. if(head != NULL)
  12. {
  13. head->next = NULL;
  14. }
  15. return head;
  16. }
  17. struct node *new_list(int data)//创建一个新的节点
  18. {
  19. struct node *new = malloc(sizeof(struct node));
  20. if(new != NULL)
  21. {
  22. new->data = data;
  23. new->next = NULL;
  24. }
  25. return new;
  26. }
  27. void list_link(struct node *head, struct node *new);//节点连接
  28. void show_list(struct node *head);//输出链表所有节点
  29. void over_turn(struct node *head);//链表翻转
  30. int main()
  31. {
  32. struct node *head;
  33. head = list();
  34. printf("请输入将要插入的整数个数:");
  35. int n;
  36. scanf("%d", &n);
  37. for(int i = 1; i <= n; i++)
  38. {
  39. struct node *new = new_list(i);
  40. list_link(head , new);
  41. }
  42. printf("翻转前:");
  43. show_list(head);
  44. over_turn(head);
  45. printf("翻转后:");
  46. show_list(head);
  47. return 0;
  48. }
  49. void list_link(struct node *head, struct node *new)//节点连接
  50. {
  51. if(head != NULL || new != NULL)
  52. {
  53. struct node *tail = head;
  54. while(tail->next != NULL)
  55. {
  56. tail = tail->next;
  57. }
  58. tail->next = new;
  59. }
  60. }
  61. void show_list(struct node *head)//输出链表所有节点
  62. {
  63. while(head->next != NULL)
  64. {
  65. head = head->next;
  66. printf("%d\t",head->data);
  67. }
  68. printf("\n");
  69. }
  70. void over_turn(struct node *head)//链表翻转
  71. {
  72. struct node *p = head->next;
  73. head->next = NULL;
  74. while( p != NULL)
  75. {
  76. struct node *temp = p->next;
  77. p->next = head->next;
  78. head->next = p;
  79. p = temp;
  80. }
  81. }

在这里插入图片描述
在这里插入图片描述

更多资料请点击:我的目录

发表评论

表情:
评论列表 (有 0 条评论,9人围观)

还没有评论,来说两句吧...

相关阅读