结构设计

就像动态数组一样,我们创建一个结构体来代表整个链表,记录链表长度,我们就可以在指定位置插入或者查找元素。整表结构体需要记录头结点地址和链表长度。

  1. typedef struct {
  2. void* data;
  3. LinkNode* next;
  4. } LinkNode;
  5. typedef struct {
  6. LinkNode pHeader;
  7. int size;
  8. } LList;
  9. typedef void* LinkList;

代码

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. typedef struct LinkNode {
  5. int data;
  6. struct LinkNode* next;
  7. } LinkNode;
  8. typedef struct LinkNode * LinkList;
  9. LinkList init();
  10. void travel(LinkList);
  11. int size(LinkList);
  12. void insert(LinkList, int, int);
  13. int main()
  14. {
  15. LinkList linkList = init();
  16. travel(linkList);
  17. insert(linkList, 10, 100);
  18. travel(linkList);
  19. return 0;
  20. }
  21. LinkList init() {
  22. LinkList linkList = (LinkList)malloc(sizeof(LinkNode));
  23. LinkNode* linkTailNode = NULL;
  24. if (linkList == NULL) {
  25. return NULL;
  26. }
  27. linkList->data = 0;
  28. linkList->next = NULL;
  29. linkTailNode = linkList;
  30. int val = -1;
  31. while (1) {
  32. printf("插入数据\n");
  33. scanf("%d", &val);
  34. if (val == 0) {
  35. break;
  36. }
  37. LinkNode * linkNode = (LinkNode*)malloc(sizeof(LinkNode));
  38. linkNode->data = val;
  39. linkNode->next = NULL;
  40. linkTailNode->next = linkNode;
  41. linkTailNode = linkNode;
  42. linkList->data += 1;
  43. }
  44. return linkList;
  45. }
  46. void travel(const LinkList const linkList) {
  47. LinkNode* currentNode = linkList->next;
  48. while (currentNode != NULL) {
  49. printf("%d,", currentNode->data);
  50. currentNode = currentNode->next;
  51. }
  52. }
  53. int size(const LinkList const linkList) {
  54. printf("%d", linkList->data);
  55. return linkList->data;
  56. }
  57. void insert(LinkList linkList, int oldVal, int newVal) {
  58. if (linkList == NULL)
  59. {
  60. return;
  61. }
  62. LinkNode *preNode = linkList;
  63. LinkNode *curNode = linkList->next;
  64. while(curNode != NULL) {
  65. if (curNode->data == oldVal)
  66. {
  67. break;
  68. }
  69. preNode = curNode;
  70. curNode = curNode->next;
  71. if (curNode == NULL)
  72. {
  73. return;
  74. }
  75. }
  76. LinkNode* newNode = (LinkNode*)malloc(sizeof(LinkNode));
  77. newNode->data = newVal;
  78. newNode->next = NULL;
  79. preNode->next = newNode;
  80. newNode->next = curNode;
  81. linkList->data += 1;
  82. }
  83. void destory(LinkList* linkList) {
  84. LinkNode* currentNode = (*linkList)->next;
  85. while (currentNode != NULL)
  86. {
  87. LinkNode* nextNode = currentNode->next;
  88. free(currentNode);
  89. currentNode = nextNode;
  90. }
  91. (*linkList)->next = NULL;
  92. *linkList = NULL;
  93. }

函数名 函数名取地址 区别

C的结构体报错