fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5. int value;
  6. struct Node *next;
  7. } Node;
  8.  
  9.  
  10. // Поиск узла по значению.
  11. // Возвращает найденный узел, а через prev записывает предыдущий.
  12. Node *find_node(Node *head, int value, Node **prev){
  13. Node *current = head;
  14. *prev = NULL;
  15. while (current != NULL) {
  16. if (current->value == value) {
  17. return current;
  18. }
  19. *prev = current;
  20. current = current->next;
  21. }
  22. return NULL;
  23. }
  24.  
  25. // Удаление узла из односвязного списка.
  26. void remove_node(Node **head, Node *node, Node *prev){
  27. if (node == NULL) {
  28. return;
  29. }
  30. if (prev == NULL) {
  31. // Удаляем первый узел
  32. *head = node->next;
  33. } else {
  34. // Перепрыгиваем через удаляемый узел
  35. prev->next = node->next;
  36. }
  37. free(node);
  38. }
  39.  
  40. int main(void){
  41. Node *head = malloc(sizeof(Node));
  42. Node *second = malloc(sizeof(Node));
  43. Node *third = malloc(sizeof(Node));
  44.  
  45. head->value = 10;
  46. head->next = second;
  47.  
  48. second->value = 20;
  49. second->next = third;
  50.  
  51. third->value = 30;
  52. third->next = NULL;
  53.  
  54. // Создаём новый узел
  55. Node *new_node = malloc(sizeof(Node));
  56. new_node->value = 25;
  57. // Вставляем его между second и third
  58. new_node->next = second->next;
  59. second->next = new_node;
  60.  
  61. // Удаление из середины
  62. // находим узел 20
  63. Node *prev = NULL;
  64. Node *node = find_node(head, 20, &prev);
  65. // удаляем найденный узел
  66. if (node != NULL) {
  67. remove_node(&head, node, prev);
  68. }
  69.  
  70. // Проходим по списку
  71. Node *current = head;
  72. while (current != NULL) {
  73. printf("%d\n", current->value);// 10 25 30
  74. current = current->next;
  75. }
  76.  
  77. // Освобождаем оставшиеся узлы
  78. current = head;
  79. while (current != NULL) {
  80. Node *next = current->next;
  81. free(current);
  82. current = next;
  83. }
  84.  
  85. return 0;
  86. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
10
25
30