如何在C ++中对用邻接表实现的图进行排序?

问题描述 投票:0回答:1

每次添加顶点时,我都尝试对其进行排序,因此,我想将添加的顶点与先前的顶点进行比较,将较高的顶点放在左侧,直到获得顶部顶点指针。

我的问题是我必须对图进行一些顶点排序的功能可以工作一点,然后在某个点停止,但是我无法弄清楚问题出在哪里,并且编译器没有返回任何错误。

这是我在添加新顶点时进行排序的功能。

void Graph::sortGraph(Vertex *pVertex){

/*
* Sort a vertex when it is insert into the graph
* Sorts it from highest to lowest
*/
while(pVertex->previous != NULL){ //Stops when the Vertex is sorted
        if(pVertex->power > pVertex->previous->power){ // To order the graph from highest to lowest
            if(pVertex->previous->previous == NULL){//If it is in position 1 and to
                graphHead = pVertex;
                pVertex->previous->next = pVertex->next;
                pVertex->next->previous = pVertex->previous;
                pVertex->next = pVertex->previous;
                pVertex->previous->previous = pVertex;
                pVertex->previous = pVertex->previous->previous;

            }
            else{ //in any other positions
                pVertex->previous->previous->next == pVertex;
                pVertex->next = pVertex->previous;
                pVertex->previous->previous = pVertex; 
                pVertex->previous->next = pVertex->next;
                pVertex->previous = pVertex->previous->previous;
            }

        } 
        pVertex = pVertex->previous; //go backwards because it have to compare the added vertex and the last one 
}

}

c++ sorting pointers graph vertex
1个回答
0
投票

这似乎是错误的:

            pVertex->previous->previous = pVertex;
            pVertex->previous = pVertex->previous->previous;

您将pVertex-> previous-> previous设置为pVertex,然后将pVertex-> previous设置为pVertex-> previous-> previous就是pVertex本身,因此pVertex-> previous是pVertex看来您创建了一个循环,但也许我错过了一些。

© www.soinside.com 2019 - 2024. All rights reserved.