There is a constant need to work with different amounts of data in C (for example, fetching information from a database and linking to a model). For a better understanding, I use structures as an analogue of objects in OOP. There is an idea to use recursive structures (a single-linked list) that will refer to the next item in the list, but for example how to sort and delete from the middle of the list is a mystery to me. In this far from being an expert, advise a solution.

  • delete is not a thing. Sort - a little harder - divided into horns, sorted halves, merged together. But I think it is better to use just a dynamic array - then sorting will be a regular library function - KoVadim
  • Use qsort cppstudio.com/post/891 and do not suffer, it is in all editions from. There everything is already implemented - only the comparison function and an array of objects are from you - nick_n_a
  • If there is a base - it is better to use order by and not to forget that in order by you can case when to attach (if different sortings are needed) -

1 answer 1

It is quite simple to delete from the middle of a single-linked list; you just need to use a pointer to the previous element:

 // Удаляем элемент p ListElem *q = listStart; // Первый элемент списка if (q != p) { // Если p не первый элемент while (q->next != p) q = q->next; q->next = p->next; } else // p это первый элемент listStart = p->next; delete p; 

Sorting is more difficult, but also not a problem:

  1. Count the number of items in the list.
  2. Create an array of pointers to elements
  3. Sorting an array of pointers according to the values ​​of the elements
  4. We loop through a sorted array of pointers, overwriting the element reference field.

Item 4 might look like this:

 // N - число элементов // R - массив указателей на элементы for (i = 0; i < (N - 1); i++) R[i]->next = R[i + 1]; R[N - 1]->next = NULL; 
  • how then to add to the middle of the list? - UjinUkr 8:55
  • @UjinUkr, according to the same principle - if there is a pointer p to the element and a pointer q to the previous element, then insert an element between them is two assignments: q = elem; elem->next = p; q = elem; elem->next = p; - freim
  • Thanks, I will try. - UjinUkr