Created
July 14, 2011 01:26
-
-
Save basicxman/1081698 to your computer and use it in GitHub Desktop.
Reverse a single linked list in O(n) time and in-place.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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