In the following code, the result of the sum is placed at the end of the list. How can I put the result of the sum at the top of the list?

List* Add_end(List* head, int index, int elm) { List* p = new List; p->num = elm; p->nItem = NULL; if (head == NULL) { head = p; } else { List* current = head; for (int i = 0; (i < index - 1) && (current->nItem != NULL); i++) { current = current->nItem; } if (index == 0) { p->nItem = head; head = p; } else { if (current->nItem != NULL) { p->nItem = current->nItem; } current->nItem = p; } } return head; } int Sum(List* head) { int sum = 0; List* p = head; while(p) { if ((p->num > 3) && (p->num < 8)) sum += p->num; p = p->nItem; } return sum; } 

    2 answers 2

    Is this your code? The function handles this situation, to add to the top of the list you need to call:

     Add_item(head, 0, sum); // где: head - голова списка // , sum - значение 

      This is the easiest :)

       p->nItem = head; head = p;