c - How to add objects to singly linked list -
information file being read car struct "newcar". need use "sll_add" function below add information single liked list of type carlist named "list". i'm having trouble understanding how starts. thank help.
int main (void)//main function { file *fp;//file pointer fp = fopen("car_inventory.txt", "r");//opens car inventory data within program. int num=0;//vairable created keep track of information. int year;//, choice;//variables use user input. char str1[100];//string created ensure program reads information original file correctly. carlist list;//creates string of type "car" named file hold 100 cars. car newcar;//car variable store info file. list *last=num; if (fp) { { while(!feof(fp))//takes input data file. { fgets(str1,50, fp); sscanf(str1,"%d %s %[^\n]s", &newcar.year, newcar.make, newcar.model); fgets(str1,50, fp); sscanf(str1,"%[^\n]s", newcar.style); fgets(str1,50, fp); sscanf(str1,"%[^\n]s", newcar.color); fgets(str1,50, fp); sscanf(str1,"%s", newcar.mileage); fgets(str1,50, fp); sscanf(str1,"%c", &newcar.air_condition); fgets(str1,50, fp); sscanf(str1,"%s", newcar.inventory_num); fgets(str1,50, fp); sscanf(str1,"%lf", &(newcar).price); fgets(str1,50, fp); sscanf(str1,"%[^\n]s", newcar.previous_owner); fgets(str1,50,fp); num++; sll_add(*newcar, &list); } } return 0; #define max_cars 100 /* type definitions */ typedef struct car { int year; char make[25]; char model[25]; char style[25]; char color[20]; char mileage[8]; char air_condition; char inventory_num[16]; double price; char previous_owner[30]; struct car *next; } car; typedef struct carlist { car *first; car *last; } carlist; void sll_init(carlist *l); car *sll_first(carlist *l); car *sll_end(carlist *l); car *sll_next(car *current, carlist *l); car *sll_retrieve(car *element, carlist *l); void sll_delete(car *c, carlist *l); void sll_delete_year(carlist *l, int year); void sll_add(car *newcar, carlist *l); #endif
start beginning. first, carlist needs initialized, need flesh out sll_init()
function. 1 easy since needs set first
, last
pointers null. might this:
void sll_init(carlist *l) { l->first = l->last = null; }
next, need able add entries list, need flesh out sll_add()
. might this:
void sll_add(car *newcar, carlist *l) { car *new = malloc(sizeof(*new)); *new = *newcar; new->next = null; // safe in case newcar wasn't initialized if (l->first == null) { // list empty, add first entry l->first = l->last = new; } else { // list not empty, append new entry end l->last->next = new; l->last = new; } }
with this, should able started.
Comments
Post a Comment