Skip to content

Instantly share code, notes, and snippets.

@cli248
Last active December 26, 2015 12:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cli248/7148518 to your computer and use it in GitHub Desktop.
Save cli248/7148518 to your computer and use it in GitHub Desktop.
Linked List Gists: (1) reverse a linked list
/*
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