我在做一个更大的程序,想在链表中实现一个链表。所以我有一个主链表,节点之间相互连接,但每个节点内部是另一个链表。我写了一些代码的方式,我认为它可以实现,但我有麻烦链接第二个链表到主链表的节点。以下是我的尝试,但我还是无法将它们连接在一起
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;
}
我希望这个示例代码输出一个有1,2,3 ....的链表有自己的节点,但在"1"节点中,我们有一个"john,bravo,gabe"的链表,"2"节点也是如此……在连接这些链表的任何帮助将是伟大的。
您的代码中有很多修复。请查看以下更改并正确修复它们。我已经解决了创建你的主链表。我不清楚你的链表在一个链表内。所以我创建了两个列表,你在你想要的地方适当地链接它!
我修改了你的逻辑,在链表的末尾添加节点。希望这对你有帮助!
尝试以下更改-
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct linked{
char* data;
struct linked *next;
};
struct node {
char* course;
struct node *next;
struct linked *head;
};
void addNode(struct node **head,char* s);
void addlinkednode(struct linked **head,char* prereq);
int main()
{
struct node *head = NULL,*temp;
struct linked *head2 = NULL,*temp1;
char* text[] = {"one", "two", "three",
"four", "five", "six"};
char* text2[] = {"john","bravo","gabe"};
int i, size = sizeof(text)/sizeof(text[0]);
int size2 = sizeof(text2)/sizeof(text2[0]);
for(i = 0; i < size; i++)
addNode(&head, text[i]);
for(i = 0; i < size2; i++)
addlinkednode(&head2,text2[i]);
// For printing...
temp=head;
while(temp){
printf("%s -> ",temp->course);
temp=temp->next;
}
printf("NULL n");
}
void addNode(struct node **head, char* s)
{
struct node* temp = malloc( sizeof(struct node) );
temp->course= malloc(sizeof(char)*10);
strcpy(temp->course, s);
if(*head == NULL){
temp->next = *head;
*head=temp;
}
else{
struct node* temp2;
temp2= *head;
while(temp2->next)
temp2=temp2->next;
temp->next=temp2->next;
temp2->next=temp;
}
}
void addlinkednode(struct linked **head,char* prereq)
{
struct linked *temp = malloc( sizeof(struct linked) );
temp->data= malloc(sizeof(char)*10);
strcpy(temp->data, prereq);
if(*head == NULL){
temp->next = *head;
*head=temp;
}
else{
struct linked* temp2;
temp2= *head;
while(temp2->next)
temp2=temp2->next;
temp->next=temp2->next;
temp2->next=temp;
}
}