0

If someone could help me find where i am going wrong, i have been working on this code for a long time but cannot get it right. It takes a linked list to be sorted by passing *head as head pointer. The output of that function should be the same linked list sorted in ascending order such that the header node will be the smallest value in the list.

void sortByCount (struct lnode** head) {

    struct lnode* temp= (*head);
    struct lnode* temp2 = (*head);

    int i;
    int j;
    int counter = 0;
    while(temp != NULL)
    {
        temp = nodeGetNext(temp);
        counter++;
    }
    for( i = 1; i<counter; i++)
    {
        temp2=(*head);
        bool flag = false;
        for(j = 1; j<counter-i+1;j++)
        {
            if(countCmp(temp2,nodeGetNext(temp2))>0)
            {
                swap(head,temp2,nodeGetNext(temp2));
            }
            if(countCmp(temp2,nodeGetNext(temp2))== 0 && (wordCmp(temp2,nodeGetNext(temp2))>0))
            {
                    swap(head,temp2,nodeGetNext(temp2));
                    flag = true;                    
                    //continue; 
            }
        }
        temp2 = nodeGetNext(temp2);
    }
}
4

1 回答 1

0

问题出在循环的这一部分:

        if(countCmp(temp2,nodeGetNext(temp2))>0)
        {
            swap(head,temp2,nodeGetNext(temp2));
        }
        if(countCmp(temp2,nodeGetNext(temp2))== 0
           && (wordCmp(temp2,nodeGetNext(temp2))>0))
        {
                swap(head,temp2,nodeGetNext(temp2));
                flag = true;                    
                //continue; 
        }

如果你决定冒泡并交换,那么第二次if检查可能会选择再次冒泡(因为交换已经发生,下一个temp2将会改变)。这可能不是您想要的。相反,您可能打算仅在第一次检查失败if时才进行第二次检查。if这通常通过在语句中添加一个else来完成。if

于 2013-02-25T22:20:49.393 回答