2012-06-26 107 views
0

我想創建一個鏈接列表,您可以在列表中輸入項目。我可以將第一個項目輸入到列表中,但是我無法在第一個項目之後添加項目而不會導致程序崩潰。有誰知道最新錯誤?C++訪問衝突寫入位置

#include <string> 
#include <iostream> 

using namespace std; 
struct node { 
    string s; 
    node *next; 
}; 
    node *root; 
    string ans; 
    node *conductor; 
void displayNodes() { 
    conductor = root; 
    while (conductor != NULL) { 
    cout<< conductor->s << endl; 
    conductor = conductor->next; 
    } 
} 
void addNode(string str) { 
    if (root == NULL) { 
     root = new node; 
     root->next = NULL; 
     root->s = str; 
     conductor = root->next; 
     return; 
    } 
    conductor->next = new node; 
    conductor = conductor->next; 
    conductor->next = NULL; 
    conductor->s = str; 
} 
void deleteNode(string str) { 
    while (conductor != NULL) { 
     if (conductor->s == str) { 
      conductor->next = conductor; 
     } else { 
      conductor = conductor->next; 
     } 
    } 
} 
int main() { 
    while (true) { 
     system("cls"); 
     cout << "Enter a string: "; 
     cin >> ans; 
     addNode(ans); 
     system("cls"); 
     displayNodes(); 
     system("pause"); 
    } 
    system("pause"); 
    return EXIT_SUCCESS; 
} 
+0

由於程序特定的錯誤,您的程序崩潰。問題不可能幫助其他人。 -1,關閉。 – Ben

回答

1

因爲你第一次設置

conductor = root->next; 

現在是NULL,並在下次嘗試

conductor->next = new node; 

這是未定義行爲

你應該做的是在第一次迭代中設置

conductor = root; 

conductor應該指向最後創建的節點,而不是指向NULL