Search code examples
listloopsinfinite

Can't detect the cause for the infinite loop


List.h

#pragma once
#include "Node.h"

using namespace std;

class List
{
protected:
Node *header;
Node *tailer;

public:
List()
{
    initList();
}

void add(string str)
{
    Node *tempNode = new Node();
    tempNode->setString(str);

    if (header->getNextNode() == tailer)
    {
        header->setNextNode(tempNode);
        tailer->setPrevNode(tempNode);
        tempNode->setNextNode(tailer);
        tempNode->setPrevNode(header);
    }

    tempNode->setPrevNode(tailer->getPrevNode());

    tailer->getPrevNode()->setNextNode(tempNode);
    tailer->setPrevNode(tempNode);

    tempNode->setNextNode(tailer);


}

virtual void printAll()
{
    Node *tempNode = header->getNextNode();

    while (tempNode != tailer)
    {
        cout << tempNode->getString() << endl;
        tempNode = tempNode->getNextNode();
    }
}



void printRev()
{
    Node *tempNode = tailer->getPrevNode();

    while (tempNode != header)
    {
        cout << tempNode->getString() << endl;

        tempNode = tempNode->getPrevNode();
    }
}

void initList()
{
    header = new Node();
    tailer = new Node();
    header->setNextNode(tailer);
    tailer->setPrevNode(header);

}
};

main.cpp

#pragma once
#include <iostream>
#include <string>
#include "List.h"
#include "Node.h"

using namespace std;


int main()
{
List list1;

list1.add("A");
list1.add("B");
list1.add("C");
list1.add("D");

//list1.printAll();

list1.printRev();

system("PAUSE");
return 0;
}

So, this is my little implementation of a linked list. I tried adding nodes and printing out all the nodes and it worked fine. But as soon as I tried to print out the nodes in a reverse order, my program goes into a infinite loop.

Can anyone tell me what I did wrong?


Solution

  • It goes wrong here

    tempNode->setPrevNode(tailer->getPrevNode());
    
    tailer->getPrevNode()->setNextNode(tempNode);
    tailer->setPrevNode(tempNode);
    

    If you add the first node, the header and tailer are the same, in the if you handle this correctly. But after the if you set the prevnode to the prevnode of tailer which is himself, which creates a loop. Also the line after creates this self loop.

    Fix those lines and it should work. I always draw these things on paper to make them more clear :)