请容忍我,我是新来的stackoverflow,所以让我试着解释我的问题,如果我的问题中有任何可以改进的地方,请一定要评论,我会编辑这个问题
好吧,我有一个链接列表,我想按列表中的一个值排序,这个值正好是价格:

tmpPtr->item->price;

我遇到的问题是转换位置,下面是代码:
struct inventory *sort_list() {
        struct inventory *tmpPtr = pFirstNode;
        struct inventory *temp = NULL;
        struct inventory *tmpNxt = pFirstNode->next;
        int tmp;
        while(tmpNxt != NULL){
               while(tmpNxt != tmpPtr){
                        if(tmpNxt->item->price < tmpPtr->item->price){
                                // if next item price is smaller than current
                                // temp for the next item
                                // heres the problem....
                                temp = tmpNxt->next;
                                tmpNxt->next = tmpPtr;
                                tmpPtr->next = temp;
                        }
                        else{
                            // if not any smaller continue
                            tmpPtr = tmpPtr->next;

                        }
                }
                tmpPtr = pFirstNode;
                tmpNxt = tmpNxt->next;
        }
        return tmpPtr;
    }

这些值并不像我从逻辑中预期的那样排序,任何指针都会很好
编辑:
struct inventory *sort_list() {
        struct inventory *tmpPtr = pFirstNode;
        struct inventory *temp = NULL;
        struct inventory *tmpNxt = pFirstNode->next;
        while(tmpNxt != NULL){
               while(tmpNxt != tmpPtr){
                        if(tmpNxt->item->price < tmpPtr->item->price){
                                // if next item price is smaller than current
                                // temp for the next item
                                if(tmpPtr == pFirstNode){
                                    tmpPtr = pFirstNode->next; // tmpPtr is now second node
                                    pFirstNode->next = tmpPtr->next;
                                    tmpPtr->next = pFirstNode;
                                    pFirstNode = tmpPtr;
                                }

                                tmpNxt = tmpPtr->next;
                                tmpPtr->next = tmpNxt->next;
                                tmpNxt->next = tmpPtr;
                                temp->next = tmpNxt;
                        }

                }
                  temp = tmpPtr;
        }
        return tmpPtr; // Place holder
    }

最佳答案

当您处于内部if状态时,您具有以下状态:
Node1 -> tmpPtr -> tmpNxt -> Node2
你想要实现的是:
Node1 -> tmpNxt -> tmpPtr -> Node2
那么您有以下代码:
temp = tmpNxt->next;/使temp = Node2
tmpNxt->next = tmpPtr;/将列表更改为Node1 -> tmpPtr <-> tmpNxt
tmpPtr->next = temp;/将列表更改为Node1 ->tmpPtrtmpNxt -> tmpPtr -> Node2
如您所见,您丢失了Node1 -> tmpNext中的链接你可以这样做并检查你的结果。

10-06 02:20