# Reversing a Doubly Linked List | Faceprep

Reversing a doubly linked list is easier when compared to reversing a singly linked list. This is because of the last node that we have in Doubly Linked Lists. Using this, we traverse from the last node and print the data elements easily.

## C code to reverse a doubly linked list

`#include <stdio.h>#include <stdlib.h>//structure of Node with prev and next pointersstruct node {doubly linked int data;struct node * prev;struct node * next;}*head, *last;void createList(int n);void displayList();void reverse_list();int main(){int n;head = NULL;last = NULL;printf("\nEnter the total number of nodes in list : "); // Input the number of nodesscanf("%d", &n);createList(n);printf("\n\nTHE DOUBLY LINKED LIST IS :\n\n");displayList();reverse_list();return 0;}void createList(int n){int i, data;struct node *newNode;if(n >= 1){head = (struct node *)malloc(sizeof(struct node));printf("\nEnter data of node 1 : ");scanf("%d", &data);head->data = data;head->prev = NULL; // HEAD nodes's prev is set to NULLhead->next = NULL; // HEAD nodes's next is set to NULLlast = head;for(i=2; i<=n; i++){newNode = (struct node *)malloc(sizeof(struct node));printf("\nEnter data of node %d : ", i);scanf("%d", &data);newNode->data = data;newNode->prev = last; // Link new node with the previous nodenewNode->next = NULL;last->next = newNode; // Link previous node with the new nodelast = newNode; // Make new node as last node}}}void displayList(){struct node * temp;int n = 1;if(head == NULL){printf("\nList is empty.\n");}else{temp = head;while(temp != NULL){printf("%d\t", temp->data);n++;temp = temp->next;}}}void reverse_list(){struct node * temp = (struct node *)malloc(sizeof(struct node));temp = last;   // Starting from the last nodeprintf("\n\nTHE REVERSED LIST IS :\n\n");while(temp != NULL){printf("%d\t",temp -> data);   //Printing the elements from the lasttemp = temp ->prev;            // Traversing reverse with the prev pointer}}`

OUTPUT

### Relevant exercises

POST A NEW COMMENT

• Input (stdin)

Output (stdout)

Input (stdin)

Expected Output

Compiler Message

Input (stdin)

`2    3`

`5`
`5`
`5`