Sunday, April 15, 2012

Sort linked list

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#define N 12 //number of elements in the array
typedef bool (*CompareFunction)(void *, void *);

typedef struct Node{
int data;
char str[20];
struct Node * next;
} Node;

/*
* create a linked list from an array of elements
*/
void createLinkedList(int array[], int length, Node **head)
{
int i;
Node *current;
Node *p;
if(length == 0)
return ;//;NULL;
for(i = 0; i < length; i++)
{
if(i == 0)
{
*head = (Node*) malloc(sizeof(Node));
(*head)->data = array[i];
snprintf((*head)->str, 10,"%d",array[i]);
(*head)->next = NULL;
current = *head;
}
else
{
p = (Node*) malloc(sizeof(Node));
p->data = array[i];
snprintf(p->str, 10, "%d", array[i]);
p->next = NULL;
current->next = p;
current = p;
}
}
}

/*
* integer compare
*/
bool compareint(void *a, void *b)
{
int x = *(int*)a;
int y = *(int*)b;
return (x > y);
}
/*
* string compare
*/
bool comparechar(void *a, void *b)
{
char *x = (char*)a;
char *y = (char*)b;
return strcmp(x, y) < 0 ? 1:0;
}

/*
* print the linked list
*/
void printLinkedList(Node *head)
{
Node *p = head;
while(p != NULL)
{
printf("(%d,", p->data);
printf("%s),", p->str);
p=p->next;
}
printf("\n");
}


bool sort(Node **head, CompareFunction cmpFunc)
{
Node *s = *head; //start node
Node *t = s->next; //iterating node
Node *t_parent = s; //parent of iterating node
Node *index = NULL; // max or min node index
Node *index_parent = NULL;
Node *current = NULL;

//iterate all nodes
while(s->next != NULL)
{
index = s;
t = s->next;
t_parent = s;
// find the max/min node
while( t != NULL)
{
if(cmpFunc(&(index->data), &(t->data)))
{
index = t;
index_parent = t_parent;
}
t_parent = t;
t = t->next;
}

//printf("index=%d\t,", index->data);

//move the seletced max/min to sorted list
if(current == NULL)
{
current = index;
*head = current;
}
else
{
current->next = index;
current = current->next;
}

//remove the selected node from the unsorted list
if(index == s)
s = s->next;
else
index_parent->next = index->next;

current->next = NULL;
}
//add the last single node in the original list to the sorted list
if(current != NULL)
current->next = s;
return true;
}



int main()
{

int array[N]={10,4,2,11,4,8,7,3,5,9,-1,2};
Node *root;
createLinkedList(array, N, &root);
printLinkedList(root);
sort(&root, &compareint);
printf("Sorted List\n");
printLinkedList(root);

return 0;
}

No comments: