简体   繁体   English

通过指针比较聚合类型的成员值

[英]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. 我对指针或者一般的c ++编程都不是很有经验。 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 ). 你的第二个循环迭代一次太多次(它运行y次并且每次执行curr = curr->next然后才访问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. 您是否尝试按顺序对列表进行排序,例如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. 因此,如果您有一个列表:9,5,8,7,6,5,4,2。并且您希望按升序排序。 You end up getting a list of: 5, 8, 7, 6, 5, 4, 2, 9. Because its only comparing two nodes and swapping them. 您最终获得了一个列表:5,8,7,6,5,4,2,9。因为它只比较两个节点并交换它们。 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. 您可能还会发现索引和迭代器在此排序中很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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