-
-
Save Equinox-/83459ca12f90681b0fd1 to your computer and use it in GitHub Desktop.
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
#include <stddef.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdio.h> | |
typedef int T; // Could be anything | |
T *firstNode = NULL; | |
T *lastNode = NULL; | |
void append(T value) { | |
// Allocate node: | |
T *ptr = (T*) malloc(2 * sizeof(T*) + sizeof(T)); // Prev addr, next addr, value | |
*(((T**) ptr) - 2) = lastNode; | |
*(((T**) ptr) - 1) = NULL; | |
memcpy(ptr, &value, sizeof(T)); | |
if (firstNode == NULL) { | |
firstNode = ptr; | |
lastNode = ptr; | |
} else { | |
*(((T**) lastNode) - 1) = ptr; | |
lastNode = ptr; | |
} | |
} | |
void insert(T *from, int n, T value) { | |
if (n <= 0) { | |
T *ptr = (T*) malloc(2 * sizeof(T*) + sizeof(T)); // Prev addr, next addr, value | |
*(((T**) ptr) - 2) = from; | |
*(((T**) ptr) - 1) = *(((T**) from) - 1); | |
memcpy(ptr, &value, sizeof(T)); | |
*(((T**) from) - 1) = ptr; | |
} else { | |
return insert(*(((T**) from) - 1), n - 1, value); | |
} | |
} | |
void print(T *node) { | |
printf("%d\n", *node); | |
T* nxt = *(((T**) node) - 1); | |
if (nxt != NULL) | |
print(nxt); | |
} | |
T get(T *from, int n) { | |
if (n <= 0) | |
return *from; | |
else | |
return get(*(((T**) from) - 1), n - 1); | |
} | |
void nfree(T *node); | |
void nfree(T *node) { | |
T* nxt = *(((T**) node) - 1); | |
if (nxt != NULL) | |
nfree(nxt); | |
free(node); | |
} | |
int main() { | |
// Append | |
append(1); | |
append(2); | |
append(3); | |
// Insert | |
insert(firstNode, 1, 4); | |
insert(firstNode, 1, 5); | |
printf("Iterate:\n"); | |
print(firstNode); | |
printf("Indexed Get: \n"); | |
printf("%d\n", get(firstNode, 3)); | |
nfree(firstNode); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment