To Reverse a doubly linked list we have two approaches either reverse the links of every node or either reverse the values of nodes. in this tutorial, we are going to reverse a doubly-linked list by reversing their links.
like if we have a doubly-linked list that has four nodes. as you see in the image given below.
after reversing this linked list the start variable refers to the last node of the list and the first node becomes the last node and the last node becomes the first node. so our new reversed linked list should be like this as you see in the image given below.
Method to Reversing a Doubly linked list
So to reverse a linked list first we need two references p1 and p2. initially, we set p1 to point to the first node of the linked list and p2 to point to the second node of the linked list.
after that, we store the p1 node’s previous link part in the p1 node’s next link part. as you see in the given below image.
and then we store the p2 node’s reference in the p1 node’s previous link part.
after that, we start a loop that will be run till the value of variable p2 does become None or Null. it means the loop will run until we reached the last node of the linked list.
in every iteration first, we store the p2 node’s next link part’s value in the p2 node’s previous link part.
second, we store the p1 node’s reference in p2 node’s next link part.
third, we set p1 to the next node that comes after node p1 using the p2 node.
fourth we set p2 to the next node that comes after node p2 using the previous link part of node p2.
so in every iteration, these four conditions will apply and this condition will run till we don’t reach the last node of the linked list or till the value of the node, p2 becomes None or Null.
so now the value of variable p2 becomes None means we reached the last node of the linked list so we store the p1 node’s reference into the start variable because the start variable always refers to the first node of the linked list.