I am trying to create a linked list where you can enter items into a list. I can enter the first item into the list but I am unable to add items after the first item without having the program crashing. Does anyone know whats wrong?
#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;
}
Because the first time you set
which is now
NULL, and at the next attemptwhich is undefined behavior.
What you should do is set
at the first iteration.
conductorshould point to the last created node, not toNULL.