Skip to content

Instantly share code, notes, and snippets.

@halit
Created April 13, 2014 19:12
Show Gist options
  • Save halit/10597934 to your computer and use it in GitHub Desktop.
Save halit/10597934 to your computer and use it in GitHub Desktop.
xored linked list
// =====================================================================================
//
// Filename: xorlinked.c
//
// Description:
//
// Version: 1.0
// Created: 04/13/2014 09:51:25 PM
// Revision: none
// Compiler: gcc
//
// Author: Halit Alptekin (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <stdlib.h>
struct Node {
struct Node* np;
void* data;
};
struct List {
struct Node* head;
unsigned int size;
};
struct List* init_list(){
struct List* new_list = (struct List*)malloc(sizeof(struct List));
new_list->size = 0;
new_list->head = NULL;
return new_list;
}
struct Node* xor_op(struct Node* first, struct Node* last){
return (struct Node*)((unsigned int)first ^ (unsigned int)last);
}
void add_elem(struct List* list, void* elem){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->np = xor_op(list->head, NULL);
new_node->data = elem;
if(list->head){
struct Node* next_node = xor_op(list->head->np, NULL);
list->head->np = xor_op(new_node, next_node);
}
list->head = new_node;
list->size++;
}
void print_list(struct List* list){
struct Node* cur = list->head;
struct Node* prev = NULL;
struct Node* next;
while(cur){
printf("%d ", (int)cur->data);
next = xor_op(prev, cur->np);
prev = cur;
cur = next;
}
}
int main(int argc, const char *argv[]){
struct List* my_list = init_list();
add_elem(my_list, (void*)5);
add_elem(my_list, (void*)6);
add_elem(my_list, (void*)7);
print_list(my_list);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment