16-nodes.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. // 定义链表节点结构体
  4. typedef struct Node {
  5. int data; // 节点存储的数据
  6. struct Node *next; // 指向下一个节点的指针
  7. } Node;
  8. /**
  9. * 向链表中插入新节点
  10. * @param head: 指向链表头节点的指针的地址
  11. * @param data: 要插入的新节点的数据
  12. */
  13. void insert(Node **head, int data) {
  14. // 创建新节点并分配内存
  15. Node *newNode = (Node *)malloc(sizeof(Node));
  16. newNode->data = data;
  17. newNode->next = NULL;
  18. // 如果链表为空,则将新节点设为头节点
  19. if (*head == NULL) {
  20. *head = newNode;
  21. } else {
  22. // 遍历链表找到最后一个节点,并将新节点连接到末尾
  23. Node *temp = *head;
  24. while (temp->next != NULL) {
  25. temp = temp->next;
  26. }
  27. temp->next = newNode;
  28. }
  29. }
  30. /**
  31. * 打印链表中的所有节点数据
  32. * @param head: 链表的头节点指针
  33. */
  34. void display(Node *head) {
  35. // 遍历链表并打印每个节点的数据
  36. Node *temp = head;
  37. while (temp != NULL) {
  38. printf("%d ", temp->data);
  39. temp = temp->next;
  40. }
  41. printf("\n");
  42. }
  43. /**
  44. * 主函数:测试链表的插入和显示功能
  45. */
  46. int main() {
  47. Node *head = NULL; // 初始化链表头节点为空
  48. // 插入三个节点到链表中
  49. insert(&head, 1);
  50. insert(&head, 2);
  51. insert(&head, 3);
  52. // 显示链表内容
  53. display(head);
  54. return 0;
  55. }