2017-01-18 27 views
0

我試圖構造一個鄰接表。我寫的代碼如下。無法將'list *'轉換爲'Node *'

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; 
     } 
    }  

    }; 

錯誤消息我得到的是: [錯誤]不能轉換名單* 'to'節點*' [錯誤]無法在初始化中將'list *'轉換爲'Node *'

+0

你並不需要執行一個鏈接列表中,你也可以使用std :: list。 – KimKulling

+0

你在哪些行上收到這些消息? – alexeykuzmin0

+0

看起來你的'list'結構應該指向'Node',而不是'list'。 – alexeykuzmin0

回答

1

我不知道,如果它只是一個錯字,但不是

struct list 
{ 
    struct list *head; 
}; 

你應該有

struct list 
{ 
    Node *head; 
}; 

因爲列表的頭是一個節點,而不是另一個列表。這將導致該行的錯誤:

Node *ptr = arr[i].head; 

因爲你試圖到列表的頭部分配(在當前的代碼是一個list*)到Node*

+0

它仍然給我在addEdge和打印功能完全相同的錯誤 – Saad

+0

@saadobaid,[不應該](http://ideone.com/EVEoJg) – SingerOfTheFall

+0

@Saad,你檢查了我以前的評論中的鏈接?這是一個ideone的鏈接,你的代碼編譯得很好 – SingerOfTheFall

相關問題