Skip to content

Instantly share code, notes, and snippets.

@pepasflo
Created August 22, 2018 20:57
Show Gist options
  • Save pepasflo/cfbf67b6ea07b99937102da9cf18e37b to your computer and use it in GitHub Desktop.
Save pepasflo/cfbf67b6ea07b99937102da9cf18e37b to your computer and use it in GitHub Desktop.
test: reverse
./reverse
reverse: reverse.c
gcc -Wall -Werror -o reverse reverse.c
clean:
rm -f reverse
.PHONY: test reverse
/*
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