What this program is supposed to do is take in user input and print them in lexicographic order using a linked linked. Say I typed in the words foo, bar, qux; the program should print out bar, foo, qux.
My problem is that whenever I insert a word, it becomes the value at the head of the node. I may have the pointers pointing in the wrong place, but I have no idea at this point.
Code:
#include <assert.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char *cstring;
typedef struct node *node_ref;
struct node {
cstring string;
node_ref link;
};
struct list list_ref;
struct list {
node_ref head;
};
void insertAscending( struct list *listref, char *input )
{
node_ref prev = NULL;
node_ref curr = (*listref).head;
if ( curr != NULL )
printf("what is listref->head %s\n", (*listref).head->string);
// Find the insertion position.
while (curr != NULL)
{
if (strcmp(curr->string, input) > 0)
{
printf("what is strcmp %d", strcmp(curr->string, input));
break;
}
/*printf("what is curr->string %s\n", curr->string);
printf("what is input %s\n", input);
printf("what is strcmp %d\n", strcmp(curr->string, input));*/
prev = curr;
curr = curr->link;
}
// Do the insertion.
node_ref temp = NULL;
temp = malloc (sizeof (struct node));
assert (temp != NULL );
temp->string = input;
temp->link = curr;
printf("%s\n", temp->string);
if (prev == NULL)
{
listref->head = temp;
printf("0\n");
}
else
{
prev->link = temp;
printf("1\n");
}
};
int main (int argc, char **argv) {
char *progname = basename (argv[0]);
char buffer[256];
int linenr;
struct list *list_ptr;
list_ptr = &list_ref;
for (linenr = 1; ; ++linenr) {
char *nlpos = NULL;
// Read a line of input and check to see if it ends with
// a newline character. Print a message if not.
char *gotline = fgets (buffer, sizeof buffer, stdin);
if (gotline == NULL) break;
nlpos = strchr (buffer, '\n');
if (nlpos != NULL) {
*nlpos = '\0';
}else
{
fprintf (stderr, "%s: %d: unterminated line: %s\n",
progname, linenr, buffer);
}
insertAscending( list_ptr, buffer );
}
for (node_ref curr = list_ptr->head; curr != NULL; curr = curr->link)
{
printf ("%s\n", curr->string);
}
return EXIT_SUCCESS;
}