Reversing a Doubly Linked List | Faceprep

10 min read

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 pointers
struct 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 nodes
scanf("%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 NULL
head->next = NULL; // HEAD nodes's next is set to NULL
last = 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 node
newNode->next = NULL;
last->next = newNode; // Link previous node with the new node
last = 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 node
printf("\n\nTHE REVERSED LIST IS :\n\n");
while(temp != NULL)
{
printf("%d\t",temp -> data); //Printing the elements from the last
temp = temp ->prev; // Traversing reverse with the prev pointer
}
}

 

OUTPUT

Reversing a Doubly Linked List

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error