Doubly link list reversal
In this blog we are going to see the code of reversal of link list
Table of contents
In doubly link list we have 3 columns.
This data consists of Address of previous node, data, and address of next node.
It is easy to use in comparison of singly link list.
It is used when we have to rearrange the dataset in natural sequence.
Creating a node
struct Node {
int data;
struct Node* next;
struct Node* prev;
}
Here we are defining the structure of node that consist of
Data that has to be inserted in the node.
Address of next node that has to be pointed.
Address of previous node that has to be pointed.
Reverse a Doubly Linked List
void reverse(struct Node** head) {
struct Node* temp = NULL;
struct Node* curr = *head;
while(curr != NULL) {
temp = curr->prev;
curr->prev = curr->next;
curr->next = temp;
curr = curr->prev;
}
if(temp != NULL) {
*head = temp->prev;
}
}
in this code we are making a function where we are reversing the link list.
In this function we are making a temporary variable whose initial value is NULL.
Here we are defining the current variable and assigning the address of head of prev so that it can point to the prev node of the link list.
In the statement
temp = curr->prev;
we are storing the previous node in the temporary variable created by the user.In the next statement
curr->prev = curr->next;
we are swapping the previous node with the next node.Following this next step ahead is
curr->next = temp;
which will point next node to previous node.And now we will continue to traverse to the next node of the list.
Adding this function in the link list code will make the one more point which will help us to print the list in the reverse order.
Complete code after adding this function goes as follows:
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}
void insert(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if(*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while(temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
}
void reverse(struct Node** head) {
struct Node *current = *head, *temp = NULL;
while(current != NULL) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if(temp != NULL) {
*head = temp->prev;
}
}
void print(struct Node* head) {
printf("Reversed doubly link list: ");
while(head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
int n, data;
printf("Enter number of nodes: ");
scanf("%d", &n);
printf("Enter %d integers to create the doubly link list: ", n);
for(int i = 0; i < n; i++) {
scanf("%d", &data);
insert(&head, data);
}
print(head);
reverse(&head);
print(head);
}