Вывести те элементы списка которые повторяются один раз - C (СИ)

Узнай цену своей работы

Формулировка задачи:

Здравствуйте. Нужно вывести те элементы двусвязного списка которые повторяются один раз
Листинг программы
  1. #include <conio.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. typedef struct list
  6. {
  7. char word[100];
  8. struct list *next;
  9. struct list *prev;
  10. }list;
  11. void creat_list(list **head, list **tail)
  12. {
  13. list *temp = (list*)malloc(sizeof(list));
  14. printf ("Enter el list:\n");
  15. scanf("%s", temp->word);
  16. temp->next = NULL;
  17. temp->prev = NULL;
  18. }
  19. list * add_to_list(list *tail)
  20. {
  21. list *temp;
  22. int f = 1;
  23. while(f)
  24. {
  25. temp = (list*)malloc(sizeof(list));
  26. printf ("Enter el list:\n");
  27. scanf ("%s", temp->word);
  28. temp->next = NULL;
  29. temp->prev = tail;
  30. temp->next = temp;
  31. tail = temp;
  32. printf ("Enter new el list - 1\n End - 0\n");
  33. scanf ("%d", &f);
  34. }
  35. return tail;
  36. }
  37. void show_el(list *temp)
  38. {
  39. printf ("%s", temp->word);
  40. }
  41. void search(list *l1_tail, list *l1_head)
  42. {
  43. int f ,i,j,n;
  44. list *prev = l1_tail;
  45. list *next = l1_head;
  46. scanf ("%d", &n);
  47. while (next != NULL)
  48. {
  49. {
  50. for(i = 0;i < n; i++)
  51. {
  52. f = 1;
  53. for (j = 0; j < n;j++)
  54. {
  55. if(!strcmp(prev->word,next->word))
  56. f = 0;
  57. break;
  58. }
  59. if (f == 1) printf("%s ", prev->word);
  60. }
  61. }
  62. }
  63. }
  64. #pragma argsused
  65. int main(int argc, char* argv[])
  66. {
  67. list *l1_head, *l1_tail;
  68. int f;
  69. setlocale (LC_ALL, "");
  70. printf ("Created new list\n");
  71. creat_list(l1_head, l1_tail);
  72. printf ("Enter new el list-1\n End - 0\n");
  73. scanf ("%d", &f);
  74. if(f)
  75. l1_tail = add_to_list(l1_tail);
  76. search (l1_tail, l1_head);
  77. getche();
  78. return 0;
  79. }
Проблема в том что я не знаю как написать функцию для того чтобы выводило только уникальные слова
Листинг программы
  1. void search(list *l1_tail, list *l1_head)
  2. {
  3. int f ,i,j,n;
  4. list *prev = l1_tail;
  5. list *next = l1_head;
  6. scanf ("%d", &n);
  7. while (next != NULL)
  8. {
  9. {
  10. for(i = 0;i < n; i++)
  11. {
  12. f = 1;
  13. for (j = 0; j < n;j++)
  14. {
  15. if(!strcmp(prev->word,next->word))
  16. f = 0;
  17. break;
  18. }
  19. if (f == 1) printf("%s ", prev->word);
  20. }
  21. }
  22. }
  23. }
Проблема где то здесь... Бьюсь над этим уже около недели, так что ваша помощь действительно последний шанс. Заранее спасибо.
Решил зайти с другой стороны и попробовать сделать сначала с числами. И неожиданно для меня получилось.
Листинг программы
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <conio.h>
  4. struct node
  5. {
  6. int num;
  7. struct node *next;
  8. };
  9.  
  10. void dup_delete(struct node **head)
  11. {
  12. struct node *p, *q, *prev, *temp;
  13. p = q = prev = *head;
  14. q = q->next;
  15. while (p != NULL)
  16. {
  17. while (q != NULL && q->num != p->num)
  18. {
  19. prev = q;
  20. q = q->next;
  21. }
  22. if (q == NULL)
  23. {
  24. p = p->next;
  25. if (p != NULL)
  26. {
  27. q = p->next;
  28. }
  29. }
  30. else if (q->num == p->num)
  31. {
  32. prev->next = q->next;
  33. temp = q;
  34. q = q->next;
  35. free(temp);
  36. }
  37. }
  38. }
  39. void create(struct node **head)
  40. {
  41. int c, ch;
  42. struct node *temp, *rear;
  43. do
  44. {
  45. printf("Enter number: ");
  46. scanf("%d", &c);
  47. temp = (struct node *)malloc(sizeof(struct node));
  48. temp->num = c;
  49. temp->next = NULL;
  50. if (*head == NULL)
  51. {
  52. *head = temp;
  53. }
  54. else
  55. {
  56. rear->next = temp;
  57. }
  58. rear = temp;
  59. printf("Do you wish to continue [1/0]: ");
  60. scanf("%d", &ch);
  61. } while (ch != 0);
  62. printf("\n");
  63. }
  64. void display(struct node *p)
  65. {
  66. while (p != NULL)
  67. {
  68. printf("%d\t", p->num);
  69. p = p->next;
  70. }
  71. printf("\n");
  72. }
  73. void release(struct node **head)
  74. {
  75. struct node *temp = *head;
  76. *head = (*head)->next;
  77. while ((*head) != NULL)
  78. {
  79. free(temp);
  80. temp = *head;
  81. (*head) = (*head)->next;
  82. }
  83. }
  84.  
  85. int main()
  86. {
  87. struct node *p = NULL;
  88. struct node_occur *head = NULL;
  89. int n;
  90. printf("Enter data into the list\n");
  91. create(&p);
  92. printf("Displaying the nodes in the list:\n");
  93. display(p);
  94. printf("Deleting duplicate elements in the list...\n");
  95. dup_delete(&p);
  96. printf("Displaying non-deleted nodes in the list:\n");
  97. display(p);
  98. release(&p);
  99. getch();
  100. return 0;
  101. }
Счастью моему не было предела и я тут же решил повторить тоже с символами и в итоге... Не получилось.
Листинг программы
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <conio.h>
  4. #include <string.h>
  5. struct node
  6. {
  7. char word[100];
  8. struct node *next;
  9. };
  10. void dup_delete(struct node **head)
  11. {
  12. struct node *p, *q, *prev, *temp;
  13. p = q = prev = *head;
  14. q = q->next;
  15. while (p != NULL)
  16. {
  17. while (q != NULL )
  18. {
  19. prev = q;
  20. q = q->next;
  21. }
  22. if (q == NULL)
  23. {
  24. p = p->next;
  25. if (p != NULL)
  26. {
  27. q = p->next;
  28. }
  29. }
  30. else if (strcmp(q->word,p->word))
  31. {
  32. prev->next = q->next;
  33. temp = q;
  34. q = q->next;
  35. free(temp);
  36. }
  37. }
  38. }
  39. void create(struct node **head)
  40. {
  41. char c[100];
  42. int ch;
  43. struct node *temp, *rear;
  44. do
  45. {
  46. printf("Enter word: ");
  47. scanf("%s", &c);
  48. temp = (struct node *)malloc(sizeof(struct node));
  49. temp->word == c;
  50. temp->next = NULL;
  51. if (*head == NULL)
  52. {
  53. *head = temp;
  54. }
  55. else
  56. {
  57. rear->next = temp;
  58. }
  59. rear = temp;
  60. printf("Do you wish to continue [1/0]: ");
  61. scanf("%d", &ch);
  62. } while (ch != 0);
  63. printf("\n");
  64. }
  65. void display(struct node *p)
  66. {
  67. while (p != NULL)
  68. {
  69. printf("%s ", p->word);
  70. p = p->next;
  71. }
  72. printf("\n");
  73. }
  74. void release(struct node **head)
  75. {
  76. struct node *temp = *head;
  77. *head = (*head)->next;
  78. while ((*head) != NULL)
  79. {
  80. free(temp);
  81. temp = *head;
  82. (*head) = (*head)->next;
  83. }
  84. }
  85.  
  86. int main()
  87. {
  88. struct node *p = NULL;
  89. struct node_occur *head = NULL;
  90. printf("Enter data into the list\n");
  91. create(&p);
  92. printf("Displaying the nodes in the list:\n");
  93. display(p);
  94. printf("Deleting duplicate elements in the list...\n");
  95. dup_delete(p);
  96. printf("Displaying non-deleted nodes in the list:\n");
  97. display(p);
  98. release(p);
  99. getch ();
  100. return 0;
  101. }
О гуру программирования, какую же сверхидиотскую ошибку я совершил?Заранее спасибо

Решение задачи: «Вывести те элементы списка которые повторяются один раз»

textual
Листинг программы
  1. #include <glib.h>
  2.  
  3. #define DELIM " \t\n"
  4.  
  5. int main(void) {
  6.     gchar * line;
  7.     GError * err = NULL;
  8.     GIOChannel * inp = g_io_channel_unix_new(0);
  9.    
  10.     if ( ! inp )
  11.         g_error("Can't create input channel!\n");
  12.    
  13.     while ( g_print("Enter some words: "), g_io_channel_read_line(inp, &line, NULL, NULL, &err) == G_IO_STATUS_NORMAL && *line != '\n' ) {
  14.         gchar ** pwrd, ** words = g_strsplit_set(line, DELIM, -1);
  15.         GSList * node, * list = NULL;
  16.        
  17.         for ( pwrd = words; *pwrd; ++pwrd )
  18.             if ( **pwrd )
  19.                 list = g_slist_prepend(list, (gpointer)*pwrd);
  20.        
  21.         g_print("Unique words:\n");
  22.         for ( node = list; node; node = g_slist_next(node) )
  23.             if ( g_slist_find_custom(list, node->data, (GCompareFunc)g_strcmp0) == node && g_slist_find_custom(g_slist_next(node), node->data, (GCompareFunc)g_strcmp0) == NULL )
  24.                 g_print("%s\n", (gchar*)node->data);
  25.        
  26.         g_slist_free(list);
  27.         g_strfreev(words);
  28.     }
  29.    
  30.     if ( err )
  31.         g_error("%s\n", err->message);
  32.    
  33.     return 0;
  34. }

Объяснение кода листинга программы

В этом коде на языке C выполняется следующая последовательность действий:

  1. Включается библиотека Glib.
  2. Определяется строка-разделитель.
  3. Создается файловый дескриптор для стандартного ввода.
  4. Проверяется возможность создания файлового дескриптора. Если это невозможно, выводится сообщение об ошибке и программа завершается.
  5. Пока пользователь вводит строку, она читается по одному слову.
  6. Слова разделяются на отдельные слова и добавляются в список уникальных слов, если они еще не были добавлены.
  7. Если слово уже есть в списке, оно игнорируется.
  8. Выводится список уникальных слов.
  9. Список уникальных слов и словаря освобождаются.
  10. Если была зафиксирована ошибка, выводится сообщение об ошибке и программа завершается.
  11. Возвращается 0, чтобы указать, что программа успешно завершилась.

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

13   голосов , оценка 4.154 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы