Skip to content

Instantly share code, notes, and snippets.

@rawcoder
Created March 23, 2014 09:45
Show Gist options
  • Save rawcoder/9720851 to your computer and use it in GitHub Desktop.
Save rawcoder/9720851 to your computer and use it in GitHub Desktop.
Heterogeneous Linked List
// Program for creating a heterogeneous linked list
// BUGS: fails for strings e.g. abc -> a (b,c are not read)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
const int SIZE = 80;
typedef enum { INT, CHAR, FLOAT } Type;
typedef struct node__ {
void* data;
Type type;
struct node__* next;
} Node;
Node* create_int (int data) {
Node* temp = NULL;
if ((temp=(Node*)malloc (sizeof (Node))) == NULL) {
fprintf (stderr, "Node creation failed in %s for data %d", __func__, data);
return NULL;
}
temp->data = malloc (sizeof(int));
*(int*)(temp->data) = data;
temp->type = INT;
temp->next = NULL;
return temp;
}
Node* create_char (char data) {
Node* temp = NULL;
if ((temp=(Node*)malloc (sizeof (Node))) == NULL) {
fprintf (stderr, "Node creation failed in %s for data %c", __func__, data);
return NULL;
}
temp->data = malloc (sizeof(int));
*(char*)(temp->data) = data;
temp->type = CHAR;
temp->next = NULL;
return temp;
}
Node* create_float (float data) {
Node* temp = NULL;
if ((temp=(Node*)malloc (sizeof (Node))) == NULL) {
fprintf (stderr, "Node creation failed in %s for data %f", __func__, data);
return NULL;
}
temp->data = malloc (sizeof(int));
*(float*)(temp->data) = data;
temp->type = FLOAT;
temp->next = NULL;
return temp;
}
Node* append_node (Node* front, Node* node) {
if (front == NULL) {
front = node;
}
else {
Node* temp = front;
while (temp->next != NULL)
temp = temp->next;
temp->next = node;
}
return front;
}
void print_list (Node* front) {
Node* temp = NULL;
for (temp = front; temp != NULL; temp = temp->next) {
switch (temp->type) {
case INT:
printf ("%d ", *(int*)temp->data);
break;
case CHAR:
printf ("%c ", *(char*)temp->data);
break;
case FLOAT:
printf ("%g ", *(float*)temp->data);
break;
}
}
putchar ('\n');
}
int main () {
Node* front;
char str[SIZE];
int i;
char c;
while (scanf("%s", str) > 0) {
if (isalpha (str[0])) {
front = append_node (front, create_char (str[0]));
}
else if (sscanf (str, "%d %c", &i, &c) > 0 && c == '.') {
front = append_node (front, create_float (strtof (str, NULL)));
}
else {
front = append_node (front, create_int (atoi(str)));
}
}
print_list (front);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment