Is there any way to reverse linked list without using temp variable in C? Thanks in advance.
the famous approach:
Element *reverse(Element *head)
{
Element *previous = NULL;
while (head != NULL) {
// Keep next node since we trash
// the next pointer.
Element *next = head->next;
// Switch the next pointer
// to point backwards.
head->next = previous;
// Move both pointers forward.
previous = head;
head = next;
}
return previous;
}
uses temp variable
Saurabh
If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable.
The recursive approach to reverse a linked list is simple, just we have to divide the linked lists in two parts and i.e first node and the rest of the linked list, and then call the recursion for the other part by maintaining the connection.
It is possible to reverse a double-linked list in O(1) by swapping it's head and tail pointers, and (depending on the implementation) setting some kind of a flag that will tell that the list should be now iterated backwards (i.e. following the back pointers to iterate forward, and following the next pointers to iterate ...
Note that your temp
usage is actually generating two swap()
calls, and can be replaced with:
swap(head->next,previous);
swap(previous,head);
You can swap without temps using xor, it is called xor swap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With