#include <iostream> #include <conio.h> using namespace std; struct list { string oldState, symbol, newState; list *next; }; list *field = NULL; list *start = NULL; void addList(string oldState, string value, string newState) { if (field == NULL) { field->oldState = oldState; field->symbol = value; field->newState = newState; field->next = NULL; //start = field; } else { while (field) { field = field->next; if (!field) field = new list; } field->oldState = oldState; field->symbol = value; field->newState = newState; field->next = NULL; } } int main() { addList("1", "2", "3"); cout << field->oldState << field->symbol << field->newState; return 0; } 

I apparently completely confused with these pointers, or something I do not understand. Explain why this is not working?

  • @Beraliv, it’s often a good idea to work with single-linked lists is to use 2 pointers in the list header. On the first and last elements of the list. In this case, to add a new item to the end of the list, you do not need to go through them all. If the order is not so important, then you can use the "stack". In this case, the new item is always added to the beginning (becomes the first) in the list. Then one list of the first element is enough to present the list. In both cases, to initialize the list, it is enough to reset the pointer to the head. - avp

1 answer 1

I fixed it like this

 #include <iostream> using namespace std; struct mylist // здесь заменил имя типа. просто list уже используется в stl. { string oldState, symbol, newState; mylist *next; }; mylist *start = NULL; void addList(string oldState, string value, string newState) { if (start == NULL) { start = new mylist(); // нужно создать элемент. Иначе ошибка. start->oldState = oldState; start->symbol = value; start->newState = newState; start->next = NULL; } else { mylist * field = start; while (field->next != NULL) { field = field->next; }; field->next = new mylist(); field = field->next; field->oldState = oldState; field->symbol = value; field->newState = newState; field->next = NULL; } } int main() { addList("1", "2", "3"); cout << start->oldState << start->symbol << start->newState; return 0; } 

Creating a new item can be made into a separate function.

  • Thank you so much - Beraliv