Skip to content

Instantly share code, notes, and snippets.

@basicxman
Created July 14, 2011 01:26
Show Gist options
  • Select an option

  • Save basicxman/1081698 to your computer and use it in GitHub Desktop.

Select an option

Save basicxman/1081698 to your computer and use it in GitHub Desktop.
Reverse a single linked list in O(n) time and in-place.
void reverseList(list **l) {
if ((*l)->next == NULL) return;
// Hold the current list pointer for use in the actual swap, then assign the
// list pointer to the next element to place us at the correct head.
list *cur = *l;
*l = (*l)->next;
// Recurse with the new list pointer. This allows us to traverse to the
// farthest element while maintaining O(n) time.
reverseList(&(*l));
cur->next->next = cur;
cur->next = NULL; // Remove the old next link.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment