C: Auto sorting double linked list
Posted: Tue Mar 30, 2010 4:36 am
This is just a little something for ultimatedragoon6 (to show how overcomplicated his implementation was), but I figured I'd share.
Code: Select all
//Simple implementation of an auto sorting double linked list
//compile with gcc -Wall -o sorted_link sorted_linked.c
//Placing this in the public domain since there is nothing original in it ;)
#include <stdlib.h>
#include <stdio.h>
struct Node
{
struct Node *next;
struct Node *prev;
int id;
};
struct Node *CreateList(int id)
{
struct Node *list = (struct Node *)malloc(sizeof(struct Node));
list->prev = NULL; //this makes list root
list->next = NULL;
list->id = id;
return list;
};
//Good ol' recursion :)
void DeleteList(struct Node *node)
{
if(node->next != NULL)
DeleteList(node->next);
free(node);
};
void DumpList(struct Node *list)
{
printf("list node: id -> %d\n", list->id);
if(list->next != NULL)
DumpList(list->next);
};
struct Node *PushToFront(struct Node *root, int id)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->prev = NULL;
newNode->next = root;
newNode->id = id;
root->prev = newNode;
return newNode;
};
struct Node *PushToBack(struct Node *root, int id)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = NULL;
newNode->id = id;
struct Node *temp = root;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
return root;
};
struct Node *Insert(struct Node *root, int id)
{
struct Node *temp = root;
int lowerID = root->id;
struct Node *insert = NULL;
while(temp->next != NULL)
{
if(temp->id <= id && temp->id >= lowerID)
{
lowerID = temp->id;
insert = temp;
}
if(temp->id > id && temp->id > lowerID) //HAS to be greater than only
break; //gone too far
temp = temp->next;
}
//we're at the end and no sign of a bigger id so just stick it on the back :)
if(temp->id <= id)
return PushToBack(root, id);
//if this is the only node
if(insert == NULL)
{
if(id <= root->id)
return PushToFront(root, id);
else
return PushToBack(root, id);
}
if(insert->next->id > id)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->id = id;
newNode->prev = insert;
newNode->next = insert->next;
insert->next = newNode;
newNode->next->prev = newNode;
}
return root;
};
int main(int argc, char *argv[])
{
if(argc <= 1)
{
printf("no arguments given\nExample:\n\tsorted_link 2 4 3 6 8 200 120\n");
exit(0);
}
struct Node *list = CreateList(atoi(argv[1]));
printf("created list\n");
printf("adding items\n");
int i;
for(i = 2; i < argc; i++)
{
list = Insert(list, atoi(argv[i]));
putchar('.');
}
putchar('\n');
DumpList(list);
DeleteList(list);
return 0;
};