Reversing a Doubly Linked List by Iteration
//Just swap the prev node value with the next node value, with the help of two pointers.
//in case there is no tail pointer, we can have temp pointer always just behind current pointer.
//after coming out of while loop, current and nextnode both will be having null value and temp-
//- will be just behind current, hence the temp will be at last node after the end of loop, hence head=temp.
DoublyLinkedListNode* reverse(DoublyLinkedListNode* head)
{
DoublyLinkedListNode*current, *nextnode, *temp;
current=head;
while(current!=0)
{
nextnode=current->next;
current->next=current->prev;
current->prev=nextnode;
temp=current;
current=nextnode;
}
head=temp;
return head;
}
Comments
Post a Comment