Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created June 12, 2011 18:01
Show Gist options
  • Save kopiro/1021819 to your computer and use it in GitHub Desktop.
Save kopiro/1021819 to your computer and use it in GitHub Desktop.
Order a book.txt alphabetically with Lists in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node* link;
struct node {
char* item;
link next;
link prev;
};
void printerr(char* s) {
printf("%s", s);
exit(EXIT_FAILURE);
}
link new_node(char* word) {
link node = malloc(sizeof(struct node));
if (node==NULL) printerr("Malloc failed");
node->item = malloc((strlen(word)+1)*sizeof(char));
if (node->item==NULL) printerr("Malloc failed");
node->next = NULL;
node->prev = NULL;
strcpy(node->item, word);
return node;
}
link insert_node(link head, link node) {
if (head==NULL) return node;
link t = head;
for(;t->next!=NULL;t=t->next);
node->prev = t;
t->next = node;
return head;
}
void print_n(link node) {
if (node->prev!=NULL && node->next!=NULL)
printf("%s <- %s -> %s", node->prev->item, node->item, node->next->item);
else if (node->prev==NULL)
printf("NULL <- %s -> %s", node->item, node->next->item);
else if (node->next==NULL)
printf("%s <- %s -> NULL", node->prev->item, node->item);
printf("\n");
}
void node_swap(link a, link b) {
char* t = malloc((strlen(a->item)+1)*sizeof(char));
if (t==NULL) printerr("Malloc failed");
strcpy(t, a->item);
strcpy(a->item, b->item);
strcpy(b->item, t);
free(t);
}
void print_l(link head) {
if (head==NULL) return;
printf("%s\n", head->item);
print_l(head->next);
}
void insertion_sort(link head) {
link t = head;
printf("Putting sentinel..\n");
for (;t->next!=NULL;t=t->next);
for (;t->prev!=NULL;t=t->prev)
if (strcmp(t->item, t->prev->item)<0)
node_swap(t, t->prev);
int i=0;
printf("Isort phases: ");
for (t=head->next->next;t->next!=NULL;t=t->next) {
printf("%d ", i++);
link j = t;
link v = new_node(t->item);
while (j->prev!=NULL && strcmp(v->item, j->prev->item)<0) {
strcpy(j->item, j->prev->item);
j = j->prev;
}
strcpy(j->item, v->item);
free(v);
}
}
int main (int argc, const char * argv[]) {
if (argc<2) printerr("Arg missing");
FILE* fp = NULL;
fp = fopen(argv[1], "r");
if (fp==NULL) printerr("Fopen failed");
link head = NULL;
char* tword = malloc(sizeof(char)*20);
if (tword==NULL) printerr("Malloc failed");
printf("Reading words..\n");
while (!feof(fp)) {
if (fscanf(fp, "%s", tword)!=EOF)
head = insert_node(head, new_node(tword));
}
fclose(fp);
free(tword);
printf("Calling Isort\n");
insertion_sort(head);
fp = NULL;
char* outfile = malloc((strlen(argv[1])+1+6)*sizeof(char));
strcpy(outfile, argv[1]);
strcat(outfile, ".order");
fp = fopen(outfile, "w");
if (fp==NULL) printerr("Fopen failed");
link t = head;
for (;t->next!=NULL;t=t->next) fprintf(fp, "%s ", t->item);
fclose(fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment