2012-06-26 104 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