2015-04-05 35 views
0

我想創建一個C++基本鏈表應用程序,但我得到這個錯誤: enter image description hereC++ EXC_BAD_ACCESS鏈表

這裏是我的節點類:

class node { 
    friend class graph; 
    int n; 
    node *next; 
}; 

,這裏是我的圖類:

class graph{ 
private: 
    node *first; 
    node *last; 
public: 
    void input(); 
    void show(); 
    graph(); 
}; 

graph::graph(){ 
    first = NULL; 
    last = NULL; 
} 

我想創建自號節點用戶插入

void graph::input(){ 
    node *n1 = new node(); 
    std::cout << "Please Enter Number \n"; 
    std::cin >> n1->n; 
    n1->next = NULL; 
    if (first==NULL){ 
     first = last = n1; 
    } 
    else{ 
     last->next = n1; 
     last = n1; 
    } 
} 

最後我想顯示數字,但我得到錯誤!

void graph::show(){ 
    node *current = first; 
    do { 
     std::cout << "///////////////\n" << current->n; 
     current = current->next; 
    }while (current->next == NULL); 
} 


int main() { 
    graph g = *new graph(); 
    g.input(); 
    g.show(); 
} 

請讓我知道如何解決這個錯誤,爲什麼我得到這個錯誤?

回答

0

我測試了你寫的代碼。正確的方法是:

void graph::show() 
{ 
    node *current = first; 
    do 
    { 
     std::cout << "///////////////\n" << current->n; 
     current = current->next; 
    }while (current != NULL); 
} 

如果while條件就像是

current->next != NULL 

那麼它將轉儲提供在列表中或在其他一些情況下,以及

+0

感謝的只有一個元素你回答 – Hamid 2015-04-05 11:05:13