c++ – Swap the maximum and minimum element in a singly linked list

Question:

It is necessary to swap the positions of the maximum and minimum element in the list. I managed to find them and display the values, but I can't swap them.

    void Find_Min_Max_SingleList (SingleList *Head) {
    double max;
    double min;
    SingleList *ptr = Head;
    min = ptr->Data;
    max = ptr->Data;
    while (ptr) {
        if (ptr->Data > max) {
            max = ptr->Data;
        }
        if (ptr->Data < min) {
            min = ptr->Data;
        }
        ptr = ptr->Next;
    }
    cout << "max: " << max << endl;
    cout << "min: " << min << endl;
}

Answer:

In principle, in this case, you can forget about the fact that this is a singly linked list and just change the values:

void Swap_Min_Max_SingleList (SingleList *Head) {
    SingleList *pmin = Head;
    SingleList *pmax = Head;
    SingleList *ptr = Head;
    while (ptr) {
        if (ptr->Data > pmax->Data) {
            pmax = ptr;
        }
        if (ptr->Data < pmin->Data) {
            pmin = ptr;
        }
        ptr = ptr->Next;
    }
    std::iter_swap(pmin, pmax); // #include <algorithm>
}

In this case, it will not work much worse than changing the links in the list, but if there is no copy constructor or calling it is expensive enough, then you will have to change the links.

Scroll to Top