Created
November 26, 2012 19:39
-
-
Save agasiev/4150163 to your computer and use it in GitHub Desktop.
Single linked list reversion
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
using namespace std; | |
struct node { | |
node * next; | |
int value; | |
}; | |
int main() | |
{ | |
node * root = new node; | |
auto a = [] { | |
static int b = 0; | |
return b++; | |
}; | |
auto print = [&](node * root) { | |
node * curr = root; | |
while (curr) { | |
printf("%d ", curr->value); | |
curr = curr->next; | |
} | |
printf("\n"); | |
}; | |
root->value = a(); | |
node * curr = root; | |
for (int i = 0; i < 10; i++) { | |
curr->next = new node; | |
curr->next->value = a(); | |
curr->next->next = NULL; | |
curr = curr->next; | |
} | |
print(root); | |
{ | |
node * prev = NULL; | |
node * curr = root; | |
node * next = root->next; | |
while (next) { | |
next = curr->next; | |
curr->next = prev; | |
prev = curr; | |
curr = next; | |
next = curr->next; | |
} | |
curr->next = prev; | |
root = curr; | |
print(root); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment