## Some of the interesting ways to reverse a linked list in place

0 / 2271 In this blog, I will cover some approaches using which, you can reverse linked list in place. Consider we have a linked list marked by the node structure below (in C language)

struct node {

int data;

struct node* ptr;

}

Below is a recursive approach for reversing the linked list and then printing it.

Below is the code snippet

## Reverse a linked list in place

NODE *result = NULL;
NODE *current = *head;
NODE *next;
while(current != NULL) {
result = current;
current = next;
}
*head = result;  // assign the reverse list back to head node of the list
The result node stores the result (the reversed linked list). Current node points to the current node while traversing and this will be used as an iterator to loop through the linked list. While traversing, we first save the next node to current in a ptr , then we link current node to the result(reverse list marked by NULL value initially as seen). We then store the current node ptr in the result(reverse list) and then increment current node ptr to point to the next node.Eventually, I assign the reverse list back to the head (first node of the list so that the list is reversed in place).
Below is the pictorial representation for better understanding.
1->2->3->4->5->NULL
current = 1
result = NULL
1->NULL
2->1->NULL
3->2->1->NULL
4->3->2->1->NULL
5->4->3->2->1->NULL
Below is the complete code to create/insert/print and reverse a linked list (another approach) using C language

## Program to create/insert print and reverse a linked list

``````#include
#include

typedef struct node
{
int data;
}NODE;

NODE *newNode = NULL;
NODE *temp = NULL;

void insert(int, NODE**);
NODE* reverse(NODE *L);

int main()
{
int i = 0;
NODE *firstNode = NULL,

for(i = 1; i <= 10; i++)
{
insert(i, &firstNode);
}

printf("The original list nn");
printList(firstNode);
printf("nn");

printf("The reversed list nn");
printList(firstNode);
printf("nn");

return 0;
}

NODE* reverse(NODE *L)
{
#if 0
NODE *first = L;
NODE *next = L->link;

else
{
//    next->link = first;
//    return;
}
printf("%d | %dn", first->data, next->data);
#endif

//    NODE *head = L;
NODE *next = NULL;
NODE *tmp = NULL;

while (L != NULL)
{
next = L;
L = tmp;
}

return next;

}

{
}
}

void insert(int data, NODE** head)
{

{
}
else
{
newNode = (NODE*)malloc(sizeof(NODE));
newNode->data = data;

}
}``````

Feel free to comment, if you have any doubts or queries.