Hello,
I'm working on a problem now that involves using Linked Lists. Input is as follows:
CS1101 CS1100
Ma1010 Ma1000
CS2132 CS1100
CS3132 CS2132
CS3132 CS2140
What I'm trying to do right now is put every single course into a linked list. Here is my code:
Code:
#include <stdio.h>
#include <string.h>
#define NODES_AT_ONCE 1000
#define NAME_LENGTH 100
struct node { char name[NAME_LENGTH]; struct node* next; };
typedef struct node Node;
static Node* freeList = NULL;
void freeNode( Node* p ) { p->next = freeList; freeList = p; }
/* This is the memory allocation function. */
Node* newNode( char* s, Node* next) {
Node * r = freeList; int i;
if ( freeList == NULL ) { /* then get space for some Nodes */
freeList = (Node*)calloc(NODES_AT_ONCE, sizeof(Node));
for(i = NODES_AT_ONCE - 1; i >= 0; i--) {
freeList[i].next = r;
r = &freeList[i];
} /* the Nodes are linked together as the freeList. */
}
freeList = r->next; strncpy(r->name, s, NAME_LENGTH); r->next = next;
return r; /* r points to the new Node which was removed from freeList */
}
void output( Node* head ) { Node* p;
for( p = head; p != NULL; p = p->next )
printf( "%s ", p->name );
printf("\n");
}
main() {
// Lists of courses
Node *crsHead = NULL, *crsTail = NULL, *noPreqHead, *noPreqTail, *crsPrintHead,
*crsPrintTail, *crsToPrintHead, *crsToPrintTail;
char buf[BUFSIZ];
char *tok;
// Loop to put all courses into a linked list
while ( fgets(buf, BUFSIZ, stdin) ) {
tok = strtok(buf, " ");
if (crsTail == NULL) crsHead = crsTail = newNode(strdup(tok),NULL);
else crsTail = crsTail->next = newNode(strdup(tok),NULL);
tok = strtok(buf, "\n");
if (crsTail == NULL) crsHead = crsTail = newNode(strdup(tok),NULL);
else crsTail = crsTail->next = newNode(strdup(tok),NULL);
}
output(crsHead);
}
Everything above main() was given to me, so it should be correct. When I run the program, the output shows:
CS1101 CS1101 Ma1010 Ma1010 CS2132 CS2132 CS3132 CS3132 CS3132 CS3132
What it appears to be doing is adding all the courses in the left column twice instead of adding one from the first column, then the one in the second column. Can someone see my error? Thanks.