Graph Representation using Linked-List

有些话、适合烂在心里 提交于 2019-12-11 19:28:52

问题


Im having some trouble trying to figure out how to get the pointers right when adding edges to a certain paired vertex.

Below is a short idea about how the linked list should look like after Vertexs and Nodes are done being Inputed.

How can i keep order on the neighborList as well? Should there be another condition if there is already a vertex edge in that current vertex?

Heres the Structured Class im trying to build:

class graph{
private:
    typedef struct node{
        char vertex;
        node * nodeListPtr;
        node * neighborPtr;

    }* nodePtr;
    nodePtr head;
    nodePtr curr;
public:
    graph();
    ~graph();

    void AddNode(char AddData);
    void AddEdge(char V, char E);
    void printList();
};

graph::graph(){
    head = NULL;
    curr = NULL;
}

// Adds a node to a linked list
void graph::AddNode(char AddData){
    nodePtr n = new node;
    n->nodeListPtr = NULL;
    n->vertex = AddData;

    if(head != NULL){
        curr = head;
        while(curr->nodeListPtr != NULL){
            curr = curr->nodeListPtr;
        }
        curr->nodeListPtr = n;
    }
    else{
        head = n;
    }
}

// takes 2 Parameters (V is pointing to E)
// I want to set it up where the neighborptr starts a double linked List basically
void graph::AddEdge(char V, char E){
    // New Node with data
    nodePtr n = new node;
    n->neighborPtr = NULL;
    n->vertex = E;
    // go to the first node in the nodeList and go through till you reach the Vertex V
    curr = head;
    while(curr->vertex != V){
        curr = curr->nodeListPtr;
    }
    //Once the Vertex V is found in the linked list add the node to the neighborPtr.
    curr->neighborPtr = n;

}


回答1:


One problem you currently have is that each node can only have one "edge" node. In your illustration, nodes A, C, and D are all possible, but node B is not without doing things a little differently.

The problem happens here:

curr->neighborPtr = n;

Every time you call AddEdge() to the same vertex, it will simply overwrite that vertex's neighborPtr. You make no effort to traverse the neighborPtrs until you find a null pointer.

Consider adding another while loop for adding edges recursively:

while (curr->neighborPtr != null)
    curr = curr->neighborPtr;
curr->neighborPtr = n;

Note that this is not the only issue in your code; you have a few places where you should be guarding against null pointers and are not. For example: in AddEdge(), what happens if the vertex V cannot be found? You are acting under the assumption that it has already been created. If it hasn't, you will end up with some null pointer errors. Keep this in mind if you are trying to make code that is robust in addition to being functional.



来源:https://stackoverflow.com/questions/18006755/graph-representation-using-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!