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
Note that your
tempusage is actually generating twoswap()calls, and can be replaced with:You can swap without temps using xor, it is called xor swap.