Skip to content

Instantly share code, notes, and snippets.

@Equinox-
Created Mar 7, 2015
Embed
What would you like to do?
#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