Try executing the code a few lines at a time.
Node temp=head; head=tail; tail=temp;
Here we just set up some variables. We exchange the head, pointing to the tail and tail to the head.
Now we define our starting node. This is our new head, which used to be a tail.
Node p=head; //create a node and point to head while(p!=null) { temp=p.next;
At this point, we will consider this (note: if this is the first iteration, next will point to zero, but it does not matter, just assume that for this case the value of N is zero): 
So, we have next , pointing to A and prev , pointing to B. We want them to be replaced. To do this, go ahead and assign next prev (which points to B), so now next and prev both point to B.
p.next=p.prev;
Excellent! We are halfway there. Now we have:

Now our last step is to prev to indicate which next to point to. How do we get to this? Fortunately, we saved what next used to indicate (in other words, A) in temp . So let me use this to assign prev .
p.prev=temp;
Alas, we have:

Now this node has been replaced, and we move on to the next.
p=p.next; }
Rinse and repeat.
Together:
Node p=head; //create a node and point to head while(p!=null) { temp=p.next; p.next=p.prev; p.prev=temp; p=p.next; }
source share