c - List structure - checking for sublist -
as i'm new c programming, i'll posting entire (not long code). tasks i've been given implement insertion of element inside list, while list stays in order, print it, , check if 1 list sublist of another. although insert , print methods work, bunch of warnings: warning: passing argument 1 of 'insert' incompatible pointer type [enabled default]|. how can fix code in order remove these warnings?
also, logically, think contains method ok, why doesn't work? work when comparing 2 lists of single element.
code looks this:
#include <stdio.h> #include "stdlib.h" typedef struct book{ int id; char name[50]; float earnings; } book; struct node{ struct book data; struct node* next; }; void insert(struct node** list, struct book k) { struct node* previous; struct node* current; struct node* newnode; newnode=(struct node*)malloc(sizeof(struct node)); newnode->data = k; newnode->next = null; if(*list==null) { *list = newnode; } else { current = *list; previous = null; while((current!=null) && current->data.earnings<k.earnings){ previous = current; current = current->next; } if(current == null) previous->next = newnode; else { if(previous == null) { newnode->next = (*list); *list = newnode; } else { previous->next = newnode; newnode->next = current; } } } } void print(struct node** list){ if((*list)==null){ printf("list empty."); return; } printf("\nlist looks this:\n"); while(*list!=null){ printf("%d\n",(*list)->data.id); printf("%s\n",(*list)->data.name); printf("%f\n",(*list)->data.earnings); *list = (*list)->next; } printf("\n"); } int contains(struct node** l1, struct node** l2){ while((*l2)!=null) { while((*l1)!=null) { if((*l1)->data.id==(*l2)->data.id && (*l1)->data.name==(*l2)->data.name) return 1; *l1 = (*l1)->next; } *l2 = (*l2)->next; } return 0; } int main() { struct book book = {5,"war , peace",100.50}; struct node** n = null; struct book book1 = {6,"anna karenina",20.5}; struct book book2 = {7,"master , margarita", 150.60}; struct node** n1 = null; struct book book3 = {6,"anna karenina",20.5}; insert(&n,book); insert(&n,book1); insert(&n,book2); print(&n); insert(&n1,book3); printf("\ndoes list2 contains list1? yes - 1, no - 0 : %d",contains(&n1,&n)); return 0; }
replace struct node** n = null;
struct node* n = null;
, same n1
what you're doing actully pass struct node*** list
, thats why warnings
for problem contains
, first compare strings use strcmp
did checked pointers, second after first loop on l1
end l1==null
won't while after first time
int contains(struct node** l1, struct node** l2) { struct node* tmp; while ((*l2) != null) { tmp = *l1; while (tmp != null) { if(tmp->data.id==(*l2)->data.id && strcmp(tmp->data.name, (*l2)->data.name) == 0) { return 1; } tmp = tmp->next; } *l2 = (*l2)->next; } return 0; }