Created
August 22, 2018 20:57
-
-
Save pepasflo/cfbf67b6ea07b99937102da9cf18e37b to your computer and use it in GitHub Desktop.
Reverse a linked-list in-place. https://www.interviewcake.com/question/c/reverse-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
test: reverse | |
./reverse | |
reverse: reverse.c | |
gcc -Wall -Werror -o reverse reverse.c | |
clean: | |
rm -f reverse | |
.PHONY: test reverse |
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
/* | |
https://www.interviewcake.com/question/python/reverse-linked-list | |
reverse a linked-list in-place. | |
*/ | |
#include <stdlib.h> | |
#include <assert.h> | |
struct Node_ { | |
void *data; | |
struct Node_ *next; | |
}; | |
typedef struct Node_ Node; | |
Node* mknode(void *data) { | |
Node* n = malloc(sizeof(Node)); | |
n->data = data; | |
n->next = NULL; | |
return n; | |
} | |
Node* rev_recur(Node *n, Node *parent) { | |
if (n->next == NULL) { | |
n->next = parent; | |
return n; | |
} else { | |
Node *new_head = rev_recur(n->next, n); | |
n->next = parent; | |
return new_head; | |
} | |
} | |
Node* reverse(Node *list) { | |
return rev_recur(list, NULL); | |
} | |
void test() { | |
Node *head = mknode("a"); | |
head->next = mknode("b"); | |
head->next->next = mknode("c"); | |
head = reverse(head); | |
assert(head->data == "c"); | |
assert(head->next->data == "b"); | |
assert(head->next->next->data == "a"); | |
} | |
int main(int argc, char **argv) { | |
test(); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment