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

처음으로 당신이 지금 NULL이며, 정의되지 않은 동작입니다 다음 시도

conductor->next = new node; 

에서

conductor = root->next; 

을 설정 때문입니다. 당신이 무엇을해야

는 첫 번째 반복에서

conductor = root; 

설정됩니다. conductorNULL이 아니라 마지막으로 생성 된 노드를 가리켜 야합니다.