Vote count:
0
For a programming assignment, we've been asked to read in some data from a text file and populate a linked list with the data. Here is the example code we've been given:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define MAX_INPUT 20
#define EXTRA_CHARS 2
typedef struct listNode
{
int data;
struct listNode * next;
} ListNode;
typedef ListNode * ListNodePtr;
int main()
{
ListNodePtr head, new, current, previous, next;
unsigned listSize;
int i, anInt;
char str[MAX_INPUT];
listSize = 0;
head = NULL;
while (fgets(str, MAX_INPUT+EXTRA_CHARS, stdin) != NULL)
{
/* Parsing the string to int */
if(sscanf(str,"%d",&anInt) != 1)
{
sprintf(str, "Invalid input entered \n");
exit(EXIT_FAILURE);
}
/* Creating the node using malloc(...) */
if ( (new=malloc(sizeof(ListNode))) == NULL)
{
fprintf(stderr,"\nMemory Allocation for ListInsert failed!\n");
fprintf(stderr,"Aborting data entry!\n");
break;
}
current = head;
previous = NULL;
/* Search to find where in insert new list node */
while (current != NULL && current->data < anInt)
{
previous = current;
current = current->next;
}
new->data = anInt;
new->next = current;
listSize++;
if (previous == NULL)
{
head = new;
}
else
{
previous->next = new;
}
}/*End of input loop */
/* Display integers in linked list */
current = head;
while (current != NULL)
{
printf("%d\n", current->data);
current = current->next;
}
/* Deallocate memory used by list nodes */
current = head;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
return EXIT_SUCCESS;
}
Here's the problem I have with it. In EVERY example of linked lists I've seen online or in books, the definition of a linked list is given as a struct that contains only one item of data and a pointer to the next node in the list. The problem is that we've been given the following structure definitions to populate with data:
typedef struct price
{
unsigned dollars;
unsigned cents;
} PriceType;
typedef struct item
{
char itemID[ID_LEN + 1];
char itemName[MAX_NAME_LEN + 1];
PriceType prices[NUM_PRICES];
char itemDescription[MAX_DESC_LEN + 1];
ItemTypePtr nextItem;
} ItemType;
typedef struct category
{
char categoryID[ID_LEN + 1];
char categoryName[MAX_NAME_LEN + 1];
char drinkType; /* (H)ot or (C)old. */
char categoryDescription[MAX_DESC_LEN + 1];
CategoryTypePtr nextCategory;
ItemTypePtr headItem;
unsigned numItems;
} CategoryType;
typedef struct bcs
{
CategoryTypePtr headCategory; /* Pointer to the next node */
unsigned numCategories;
} BCSType;
This does not fit in with all the examples I've seen. So in the "generic" code above, do I have to do everything above, but replace the "new->data" part with, for example, "category->categoryID", and "category->categoryName" etc etc for all the members of the struct in order to populate the entire linked list with data?
Adapting generic code to different size of linked list in C
Aucun commentaire:
Enregistrer un commentaire