im working on a larger program and wanted to implement a linked list inside a linked list. So that i have a main linked list with nodes connecting to each other, but inside each node is another linked list. I wrote some code of the way i think it could be implemented but im having trouble linking the second linked list into the node of the main linked list. The following is my attempt but again im having trouble connecting them all together
struct node {
char* course;
struct node *next;
struct linked *head;
};
struct linked{
char* data;
struct linked *next;
};
struct node* addnode(struct node *head,char* s);
struct node* addlinkednode(struct node *head,char* prereq);
int main()
{
struct node *head = NULL;
struct node *head2 = NULL;
char* text[] = {"one", "two", "three",
"four", "five", "six"};
char* text2[] = {"john","bravo","gabe"};
int i, size = sizeof(text)/sizeof(text[0]);
size2 = sizeof(text2)/sizeof(text2[0]);
for(i = 0; i < size; i++)
head = addNode(head, text[i]);
head2 = head
for(i = 0; i < size2; text2[i])
head2 = addlinkednode(head2,text2[i]);
}
struct node* addNode(struct node* head, char* s)
{
struct node* temp = malloc( sizeof(struct node) );
strcpy(temp->course, s);
temp->next = head;
return temp;
}
struct node* addlinkednode(struct node *head,char* prereq)
{
struct linked *temp = malloc( sizeof(struct node) );
strcpy(temp->data, prereq);
temp->next = head;
return temp;
}
i would like this example code to output a linked list with one,two,three.... being there own node, but inside the "one" node we have a linked list of "john,bravo,gabe", same goes for the "two" node etc... any help in connecting these linked list would be great.
head2->head = addlinkednode(head2->head, text2[i]);. However the strcpy in your addNote functions might not do what you want (don't use strcpy), and you are adding nodes at the beginning of the list instead of the end. Also you should check for malloc() return value, and finally you need to alloc your string inside your node.strcpy(temp->course, s);isn't looking too hot whentemp->courseinaddNodeis an indeterminate target. You never allocated memory for the copy (you allocated space of for the node, but the pointer within is still indeterminate), so that line invokes undefined behavior. The same is true forstrcpy(temp->data, prereq)inaddlinkednode.for(i = 0; i < size2; text2[i])here I think you should usei++instead oftext2[i].free()all those allocations) to you. Best of luck.