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

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree