Create a reverse LinkedList in C++ from a given LinkedList
I'm having some trouble create a linkedlist in reverse order from a given linkedlist.
I come from a java background, and just started doing some C++.
Can you check out my code and see what's wrong? I'm guessing I'm just manipulating pointer and not creating anything new.
//this is a method of linkedlist class, it creates a reverse linkedlist
//and prints it
void LinkedList::reversedLinkedList()
{
Node* revHead;
//check if the regular list is empty
if(head == NULL)
return;
//else start reversing
Node* current = head;
while(current != NULL)
{
//check if it's the first one being added
if(revHead == NULL)
revHead = current;
else
{
//just insert at the beginning
Node* tempHead = revHead;
current->next = tempHead;
revHead = current;
}
current = current->next;
}//end while
//now print it
cout << "Reversed LinkedList: " << endl;
Node* temp = revHead;
while(temp != NULL)
{
cout << temp->firstName << endl;
cout << temp->lastName << endl;
cout << endl;
temp = temp->next;
}
}//end method
Easier one: Go through your linked list, save the previous and the next node and just let the current node point at the previous one:
void LinkedList::reversedLinkedList()
{
if(head == NULL) return;
Node *prev = NULL, *current = NULL, *next = NULL;
current = head;
while(current != NULL){
next = current->next;
current->next = prev;
prev = current;
current = next;
}
// now let the head point at the last node (prev)
head = prev;
}
Node* revHead;
// ...
while(current != NULL)
{
//check if it's the first one being added
if(revHead == NULL)
You don't initialize revHead
but you use it.
(I hope it is already clear to you that revHead
is a local variable used to store a memory address, and not something that exists outside the method/procedure)
The Storage Class of revHead
is automatic (aka in the local scope-body). In C++
when you do a declaration like that, there is not guarantee that the value will be 0
.
(unless the storage class is of type static
or the variable is global
where it is automatically initialized to 0
if no other value is provided. In your case the variable has storage class of type auto
which means it is locally defined in a function, and when declaring a local variable, without specifying a value, the value is garbage. Keep in mind that with the next C++ Standard C++0x
the keyword auto
has a new meaning).
The value in your case is garbage which makes the if
fail. See more Information here : Link
Do a
Node* revHead = NULL;
Keep in mind that maybe you may have errors like that in other part of your code as well.