У меня возникли проблемы с программированием двусвязного списка. Проблема в том, что моя функция Add приводит к бесконечному циклу, когда я проверяю ссылки на nullptr. Когда я этого не делаю, это дает мне ошибку. Я пытался исправить это, и для жизни я не могу понять это. Ниже приведен метод добавления:
void Add(string n, int w) //Method to add a node to the Linked List and maintain the order.
{
node * nd = new node(n, w, nullptr, nullptr);
if (nHead == nullptr && wHead == nullptr) //If there is nothing in the Linked List
{
nHead = nd; //Add a node
wHead = nd;
}
else //If there is something in the linked List
{
node * ntraverse = nHead; //variable to traverse down the name links
while (nd->name > ntraverse->name && ntraverse->wLink != nullptr)
{
ntraverse = ntraverse->nLink; // Traverses down the name links until nd's name is smaller than a links
}
nd->nLink = ntraverse; // Here, the namelink for nd is set to ntraverse, since ntraverse is less than or equal to nlink
ntraverse->nLink = nd; // So here, since nd is the new value appended to the rest of the list, we set ntraverse = nlink.
// note at this point, we have not handled weight
node * wtraverse = wHead; //variable to traverse down the weight links
while (nd->weight > wtraverse->weight && wtraverse->wLink != nullptr)
{
wtraverse = wtraverse->wLink; // Traverses down the weight links until nd's weight is smaller than a links
}
nd->wLink = wtraverse; // Here, the namelink for nd is set to ntraverse, since ntraverse is less than or equal to nlink
wtraverse->wLink = nd; // So here, since nd is the new value appended to the rest of the list, we set ntraverse = nlink.
//at this point, nd holds both the correct nlink and wlink
}
cout << "Added: " << nd->name << " " << nd->weight << "\n";
cout << "Current nlist:\n";
nPrint();
cout << "Current wlist:\n";
wPrint();
size++; //increment size
}
Любая помощь приветствуется. Если вам нужно, чтобы я что-то ответил, пожалуйста, дайте мне знать. Node работает нормально, он хранит 4 значения: имя, вес, nLink и wLink, где nLink хранит список, упорядоченный по имени, а wLink сохраняет список, упорядоченный по весу. Для LinkedList nHead — заголовок имени, а wHead — заголовок веса.
Еще раз спасибо за вашу помощь.
nullptr
- person Stephen Reindl   schedule 07.10.2016