J'ai eu des problèmes pour programmer une liste doublement chaînée. Le problème est que ma fonction Add aboutit à une boucle infinie quand je vérifie si les liens sont nullptr. Quand je ne le fais pas, cela me donne une erreur. J'ai essayé de régler cela et pour la vie de moi ne peux pas le comprendre. Voici la méthode d'addition:Ajouter une fonction dans une liste doublement liée entraîne une boucle infinie
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
}
Toute aide serait grandement appréciée. Si vous avez besoin de moi pour répondre à quelque chose, s'il vous plaît faites le moi savoir. Le nœud fonctionne correctement, il stocke 4 valeurs: nom, poids, nLink et wLink, où nLink conserve la liste ordonnée par nom et wLink conserve la liste ordonnée au poids. Pour LinkedList, nHead est la tête de nom et wHead est la tête de poids.
Encore une fois, merci pour votre aide.
Je suppose que c'est "C" ou "C++"? Veuillez ajouter les tags appropriés. Si oui, ce qui est 'nullptr' –
C++, La raison pour laquelle j'ai ajouté nullptr est que je pensais que quelque chose pourrait mal se passer lors de la vérification des liens pour nullptr. – Paul