A doubly-linked list is a type of linked list that comes with an additional pointer to the previous node. It works the same as a singly linked list, but each node in a doubly-linked list is connected with its previous and next node through a pointer.
Note: Want to learn about linked list? Click here for more info.
Let's consider we get a doubly-linked list and we need to reverse it so that the pointer currently pointing to the head of the list points to the tail of the doubly-linked list. Moreover, other pointers also start pointing to the previous node. In this answer, we'll learn to reverse a doubly-linked list. Here's the visualization of reversed doubly-linked list:
Here are the steps required to reverse the doubly-linked list:
Create a temporary node and temporary head node.
Use a loop to traverse throughout the doubly linked list.
Swap the values of the temporary node and the current node.
Update the value of the head pointer.
Here's a step-by-step implementation of reversing a doubly linked list. For reversing, we use a simple swapping function to swap the values of nodes until we reach the tail.
/* Reversing a Doubly Linked List */void reverse_list(node **head_ptr){//Creating temporary nodenode *temp_node = NULL;node *current_node = *head_ptr;/* swapping next and previous pointers until all nodes are reversed */while (current_node != NULL){ //swappingtemp_node = current_node->prev;current_node->prev = current_node->next;current_node->next = temp_node;current_node = current_node->prev;}if(temp_node != NULL ) //update head_ptr*head_ptr = temp_node->prev;}// Driver Codeint main(){node* head = new node(); //creating headhead->data=1; //intializing head's value with 1head = addAtEnd(head, 2); //Inserting new nodeshead = addAtEnd(head, 3);head = addAtEnd(head, 4);print_data(head); //displaying whole listreverse_list(&head); //reverseing listcout<<"\n\nAfter reversing \n\n";print_data(head); //displying whole list}
Line 3–7: We define a reverse_list()
function with a parameter of the address pointer *head_ptr
. We create temporary nodes to traverse the doubly-linked list.
Line 9–14: We use while
loop to iterate through each node and in while
we swap the values of prev
, next
, and current_node
.
Line 16–17: We update the value of head_ptr
for the next iteration.
We completely reversed the given doubly-linked with the time complexity being
Free Resources