So I'm trying to create a linked list consisting of a class. I'm not using a lot of the functions which I defined but I'm going to post my code in it's entirety anyway. In fact you should ignore the functions "insert", "disp", and "reverse" since they're not being used.
#include <iostream>
#include "test4.h"
usingnamespace std;
int main()
{
Node* head;
head = new Node();
head->set_link(head);
if(head->get_link() == head)
{
cout << "head is linked to head\n";
cout << "address: " << head << endl;
cout << "link: " << head->get_link() << endl << endl;
}
//disp(head);
for(short i = 1; i < 11; i++)
{
donut_insert(head, i);
}
short i = 0;
Node* dispPtr;
dispPtr = head;
while(dispPtr != NULL && i<8 && dispPtr->get_link() != head)
{
cout << "number: " << dispPtr->get_number() << " link: " << dispPtr->get_link() << endl;
dispPtr->set_link(dispPtr->get_link());
i++;
}
cout << "Enter key to exit: ";
char a;
cin >> a;
return 0;
}
The code compiles but the loop on line 28 causes only the first node to be displayed. It's as if though my function "donut_insert" doesn't pass the argument "head" as a reference argument but I think it should because I included &, unless that's not how you do it with pointers. What's wrong with my code?
while(dispPtr != NULL && i<8 && dispPtr->get_link() != head)
{
cout << "number: " << dispPtr->get_number() << " link: " << dispPtr->get_link() << endl;
//dispPtr->set_link(dispPtr->get_link()); //here you are breaking your structure
dispPtr = dispPtr->link; //stupid getters and setters that make your members public
i++;
}
You weren't updating dispPtr.
You ought to encapsulate the behaviour in a class circular_list. Also, check out for memory leaks
"Enter key to exit: " ¿how many times do you think that I pressed 'Enter'? xP
You are absolutely right. Thank you! This is a bit embarrassing to admit but I've spent a whole day on this code (this is my second or third attempt)! what a humbling experience this was. What doesn't kill you makes you stronger I suppose. Thank you for taking the time to sift through all that.