无法在作业

时间:2017-01-18 08:09:51

标签: c++ graph

我正在尝试构建一个邻接列表。我写的代码如下。

struct Node
{
    int dest;
    struct Node* next;  
};

struct list
{
    struct list *head;
};

该类定义为:

class Graph
{
    private:
        int vertix;
        list *arr;
    public:
        Graph(int v)
        {
            vertix = v;
            arr = new list [vertix];
            for(int i=0;i<vertix;i++)
            {
                arr[i].head=NULL;
            }
        }

        Node* getNewNode(int destination)
        {
            Node* newNode = new Node;
            newNode->dest = destination;
            newNode->next = NULL;
            return newNode;
        }

错误在于以下功能:

        void addEdge(int src, int dest)
        {
            Node* newNode = getNewNode(dest);
            newNode->next = arr[src].head;
            arr[src].head = newNode;

            newNode = getNewNode(src);
            newNode->next = arr[dest].head;
            arr[dest].head = newNode;

        }
    void print()
    {
        cout<<"Adjacency list of vertix: "<<endl;
        for(int i = 0; i< vertix; i++)
        {
            Node *ptr = arr[i].head;
            cout<< i << "-->";
            while(ptr)
            {
                cout<< "-->"<<ptr->dest;
                ptr=ptr->next;
            }
            cout<<endl;
        }
    }    

  };

我得到的错误消息是: [错误]无法在分配中将'list *'转换为'Node *' [Error]无法在初始化

中将'list *'转换为'Node *'

1 个答案:

答案 0 :(得分:1)

我不确定这只是一个错字,而不是

struct list
{
    struct list *head;
};
你应该

struct list
{
    Node *head;
};

因为列表的头部是节点,而不是另一个列表。这会导致此行中的错误:

Node *ptr = arr[i].head;

因为您尝试将列表的头部(当前代码中的list*)分配给Node*