I tried avoiding to ask this question here, however after almost an hour looking at the same piece of code I really have no idea why the following code fails to reverse a doubly linked list:
Node* Reverse(Node* head) {
if (head == nullptr) {return head;}
Node *iter = head, *tail, *newTail;
while (iter -> next != nullptr) {iter = iter -> next;} //to set the tail pointer
tail = iter;
newTail = tail; //the node that will become the tail after reversing is done
iter = head;
while (iter != tail) {
newTail -> next = iter;
iter -> prev = newTail;
newTail = iter;
iter = iter -> next;
}
newTail -> next = nullptr;
tail -> prev = nullptr;
return tail;
}
I would appreciate any help.
EDIT It seems that the code has nothing to do with what I had in mind. Wow. As a side note, I have completed only the introductory programming course which doesn't cover pointers, let alone linked lists etc. Thank you for your help!
FINAL CODE If you are interested, I have finished my algorithm for reversing a doubly linked list. I think it is a nice approach, although I am open for suggestions of course.
node *reverse(node *head)
{
if (head == nullptr) {return head;}
node *iter, *tail, *temp, *newTail;
while (iter -> next != nullptr) {iter = iter -> next;}
tail = iter;
newTail = tail;
iter = tail -> prev;
while (iter != nullptr)
{
temp = iter -> prev;
newTail -> next = iter;
iter -> prev = newTail;
newTail = iter;
iter = temp;
}
tail -> prev = nullptr;
newTail -> next = nullptr;
return tail;
}
