简体   繁体   中英

Comparing member values of aggregate type via pointer

I am having some issues with sorting nodes in a linked list. I am able to successfully implement the list itself, but when I attempt to sort it I fail. I believe this is an issue related to my attempt at comparing deferenced pointers of aggregate type. I'm not very experienced with pointers, or c++ programming in general really. If anyone could help point me in the right direction I would greatly appreciate it.

void sortNodes()
{
    int y, tmp;
    y = nodeCount();
    Node *curr, *prev;

    for (int i = 0; i < y; i++)
    {
        curr = root;
        for (int j = 0; j < y; j++)
        {
            prev = curr;
            curr = curr->next;
            if (prev->x > curr->x)
            {
                tmp = prev->x;
                prev->x = curr->x;
                curr->x = tmp;
            }
        }
    }
    curr = 0;
    prev = 0;
}

your second loop iterates one too many times (it runs y times and executes curr = curr->next every time before accessing curr->x ). Also, you don't have to run the second loop all the way to the end every time, after the first run the last node will contain the maximum value, after two runs the two last nodes will have the maximum values, etc.

Otherwise it looks like a fine bubblesort to me. If you're into that sort of thing...

Are you trying to sort a list in order thus something like, 1, 2, 3, 4, ,5...n. If so, I would like to point out that your code will only sort the current element with the next element. Rather than sorting the entire list. So if you have a list of: 9, 5, 8, 7, 6, 5, 4, 2. And you want to sort in ascending order. You end up getting a list of: 5, 8, 7, 6, 5, 4, 2, 9. Because its only comparing two nodes and swapping them. If you want to sort the entire list, you need another loop that loops backward to the root as long as the current element is less than the previous element. You might need another function than loops backward, pushing the previous node to current node until the previous node is less than the temp node. You might also find that index and an iterator useful in this sorting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM