# An interesting method to print reverse of a linked list

We are given a linked list, we need to print the linked list in reverse order.

Examples:

```Input : list : 5-> 15-> 20-> 25
Output : Reversed Linked list : 25-> 20-> 15-> 5

Input : list : 85-> 15-> 4-> 20
Output : Reversed Linked list : 20-> 4-> 15-> 85

Input : list : 85
Output : Reversed Linked list : 85

```

For printing a list in reverse order, we have already discussed Iterative and Recursive Methods to Reverse.

In this post, an interesting method is discussed, that doesn’t require recursion and does no modifications to list. The function also visits every node of linked list only once.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Trick : Idea behind printing a list in reverse order without any recursive function or loop is to use Carriage return (“r”). For this, we should have knowledge of length of list. Now, we should print n-1 blanck space and then print 1st element then “r”, futher again n-2 blank space and 2nd node then “r” and so on..
Carriage return (“r”) : It commands a printer (cursor or the display of a system console), to move the position of the cursor to the first position on the same line.

```// C program to print reverse of list
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

/* Function to reverse the linked list */
void printReverse(struct Node** head_ref, int n)
{
int j = 0;
while (current != NULL) {

// For each node, print proper number
// of spaces before printing it
for (int i = 0; i < 2 * (n - j); i++)
printf(" ");

// and print.
printf("%dr", current->data);

current = current->next;
j++;
}
}

/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));

new_node->data = new_data;
}

/* Function to print linked list and find its
length */
{
// i for finding length of list
int i = 0;
while (temp != NULL) {
printf("%d  ", temp->data);
temp = temp->next;
i++;
}
return i;
}

/* Driver program to test above function*/
int main()
{
// list nodes are as 6 5 4 3 2 1

// printlist print the list and
// return the size of list

// print reverse list with help
// of carriage return function

return 0;
}
```

Output:

```Given linked list:
6 5 4 3 2 1
1 2 3 4 5 6
```

Input and Output Illustration :

NOTE:Above program may not work on online compiler because they do not support anything like carriage return on their console.

Reference :

stackoverflow/Carriage return

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.6 Average Difficulty : 1.6/5.0
Based on 3 vote(s)