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.
1 answer
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:
- Count the number of items in the list.
- Create an array of pointers to elements
- Sorting an array of pointers according to the values of the elements
- 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
|
order byand not to forget that inorder byyou cancase whento attach (if different sortings are needed) -