I've created a function in C to reverse a singly-linked list in place:
typedef struct n {
int key;
struct n* next;
} node;
node* inplaceReverse(node* head, int index) {
if(!head || !head->next) {
/* Indication of last node (or empty list). This will be recursively returned to become the new head pointer of the reveresed list. */
return head;
}else {
/* Reverse the list after head and store its return in tmp. */
node* newhead = inplaceReverse(head->next,index+1);
/* Make the next node's next point to head. */
head->next->next = head;
/* If head was the first node, make its next NULL. */
if(!index) head->next = NULL;
return newhead;
}
}
It works but one thing that bothered me is that I needed to create an additional argument for the actual function (int index
). This is to indicate the original head of the list so I know which one to set to NULL
after the reverse. It feels like there's an obvious and better way to do this but I'm not sure.
Other suggestions for optimization and improvements are also welcomed.