/*
Reverse a singly linked list without recursion.
The argument may be NULL.
Returns the new head of the list.
Runs in linear time and with constant memory usage.
*/
node *rev( node *head ) {
node *next;
node *curr = head;
node *prev = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
It is one of those "see how stupid smart my interviewee is" questions.
It is a variation on the "how to exchange two variables without a temporary" tricks. Which, in an interview, I would answer is a stupid thing to do because it makes assumptions about the underlying data & pointer/integer conversions.
To exchange two integers without a temporary, use XOR: a ^=b, b ^= a, a ^= b;