C++/circular link list
Expert: Zlatko - 2/23/2010
QuestionQUESTION: I try with this code..
but still cannot make it..
help..me sir..Thanks
void List::DisplayList()
{
int num = 0; //initialize counter for number of data in the list
Node* currNode = head;
Node* lastNode = NULL;
while (lastNode->next != head)
{
cout << currNode->data << endl; //display each element
currNode = currNode->next; //tetpkan nilai next node as the currNode
num++; //increase counter
}
cout << "Number of nodes in the list: " << num << endl;
}
ANSWER: If you set lastNode to null, you cannot then ask what lastNode->next is because you cannot go "through" a NULL pointer.
Here is how you do it.
Set currNode to head
print currNode
go to currNode->next
Put the last 2 steps into a loop.
When do you stop ? When you're back at the head.
What will you do if head is NULL ?
---------- FOLLOW-UP ----------
QUESTION: If head == NULL then there will be nothing to be print
Is this true sir??
but it still cant print the correct output..
fuh..
void List::DisplayList()
{
int num = 0; //initialize counter for number of data in the list
Node* currNode = head;
if( head == NULL)
// {
cout<<"Link list is empty"<<endl;
// return true;
// }
else
{
cout << currNode->data << endl;
currNode = currNode->next;
while (currNode == head)
{
cout << currNode->data << endl;
currNode = currNode->next;
num++; //increase counter
}
cout << "Number of nodes in the list: " << num << endl;
}
}
AnswerThat's pretty good, but your num value is one less than it should be because the first node is printed outside of the loop. Also while(currNode==head) should be while(currNode != head).
Below is a more compact way of doing it using some of your older code.
Good luck with the rest of your program. I can help you again around the same time tomorrow.
Good night.
void List::DisplayList()
{
int num = 0; //initialize counter for number of data in the list
Node* currNode = head; //initialize start currNode dr head
if (currNode == NULL)
{
cout<<"Link list is empty"<<endl;
}
else
{
do
{
cout << currNode->data << endl; //display each element
currNode = currNode->next; //tetpkan nilai next node as the currNode
num++; //increase counter
}
while (currNode != head);
}
cout << "Number of nodes in the list: " << num << endl;
}