Last active
December 26, 2015 12:08
-
-
Save cli248/7148518 to your computer and use it in GitHub Desktop.
Linked List Gists: (1) reverse a linked list
This file contains 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
/* | |
Credit to Leetcode: http://leetcode.com/2010/04/reversing-linked-list-iteratively-and.html | |
*/ | |
struct Node { | |
int val; | |
Node *next; | |
Node(int value):val(value), next(NULL) {}; | |
}; | |
Node* reverse(Node* head) { | |
Node *curr = head; | |
Node *prev = NULL; | |
while (curr) { | |
Node *next = curr->next; | |
curr->next = prev; | |
prev = curr; | |
curr = next; | |
} | |
return prev; | |
} | |
void reverseRecursive(Node*& p) { | |
if (p == NULL) | |
return; | |
Node *rest = p->next; | |
if (rest == NULL) | |
reutrn; | |
reverseRecursive(rest); | |
p->next->next = p; | |
p->next = NULL; | |
p = rest; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment