Printing my linked list in reverse order in C++
Within printList
, you have to also check for head == NULL
, otherwise you are acessing members of a pointer pointing to NULL
. The following should work.
void printList()
{
node *temp = head;
while(temp != NULL) // don't access ->next
{
cout << temp->data << endl;
temp = temp->next;
}
}
In printReverse()
I really can't understand why you take half of the counts of the elements to print and print two elements in every iteration. However, you really don't need a for-loop here. You can simply stop as soon as temp == head
after your loop, since then you just printed the head. And only print one element, the one whose next pointer points to the previously printed element.
Another, recursive, attempt to solve the problem looks like this:
void printReverse()
{
printReverseRecursive(head);
}
void printReverseRecursive(node *n)
{
if(n) {
printReverseRecursive(n->next);
cout << n->data << endl;
}
}
You should consider re-writing your loop to start at the last element (as you have done) and have your loop condition stop when you reach the head
. Having double the code inside your for
loop, along with the odd count/2
logic is certainly confusing you (and us).
temp = [last element]
while not at head
print temp
temp = previous element
print head
Note that you already have the code for the temp = previous element
part:
temp2 = head;
while(temp2->next != temp)
temp2 = temp2->next;
Since I assume this is an assignment of some type, I'm intentionally not giving you the c++ code for this. Even if it isn't assignment, working through it with this in mind should be the learning experience you're after. However, if you give it a shot and still have a problem, feel free to update your question (or post a new one).
void printReverse()
{
printReverse(head) //kickstart the overload function below
}
void printReverse(node *n)
{
if(n == 0) return;
printReverse(n->next); //print the next
cout << n->data << endl; //before printing me
}