To my task, I wrote such a delete function.

void Delete(list *head, list* &tail) { list *T, *P; P = head; T = head->next; while (T->next != tail) { if (T->info == P->info) P->next = T->next; // если элементы одинаковые то убираю 2 одинаковый else P=T; // если разные то двигаюсь дальше T = T->next; } if (tail->info == T->info) // рассматриваю последний и предпоследний { T->next = NULL; // если одинаковые то последний убираю tail = T; } } 

everything seems to be provided, but there is no desired result at the output (for example, I entered 8 units, then it turns out 2 units, and not one, when in some cases everything works out (for example, I enter 1 2 2 3 3 goes 123). Please indicate the error .

  • I'm there to your question "dynamic structure" a little bit answered. - avp

2 answers 2

Error Code

  1. The case when the list consists of one element is not considered, that is, head->next is NULL .
  2. There is a memory leak for items that are excluded from the list.
  3. The tail argument is not needed. More precisely, it is needed only if duplicates need to be searched not in the entire list, but in its part. And the end of the list can always be recognized by the fact that for the last element the next pointer will be set to NULL .
  4. There are extra variables. The same P pointer is not needed, since the head pointer in the function cannot be changed. And you can only change the data on the head po.
  5. Well, and to a heap - the algorithm too screw up. There is no need to separately consider the last and the penultimate element. Just like the first and second. Try to manually run the algorithm for a list of two identical elements - I think you will understand everything

    Here is an example of a working function, you rework for your example. The complexity is O (n 2 ) .

     Node* removeDuplicates(Node *head) { Node *t, *p, *i, *prev; for(p = head; p != NULL; p = p->next) { prev = p; for(i = p->next; i != NULL; ) { if(i->data == p->data) { t = prev->next = i->next; free(i); i = t; continue; } prev = i; i = i->next; } } return head; }