帮我改进这个代码,要求程序在主函数中循环生成多个链表,并把每个链表存放在plist结构体数组中
时间: 2023-03-28 15:04:56 浏览: 69
好的,我可以回答这个问题。以下是改进后的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_LISTS 10 // 最多链表数量
typedef struct node {
int data;
struct node *next;
} Node;
typedef struct plist {
Node *head;
Node *tail;
} PList;
void initList(PList *list) {
list->head = NULL;
list->tail = NULL;
}
void addNode(PList *list, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
} else {
list->tail->next = newNode;
list->tail = newNode;
}
}
void printList(PList *list) {
Node *current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
PList plist[MAX_LISTS];
int numLists, numNodes, data;
printf("请输入链表数量:");
scanf("%d", &numLists);
for (int i = ; i < numLists; i++) {
initList(&plist[i]);
printf("请输入第%d个链表的节点数量:", i+1);
scanf("%d", &numNodes);
for (int j = ; j < numNodes; j++) {
printf("请输入第%d个节点的值:", j+1);
scanf("%d", &data);
addNode(&plist[i], data);
}
printf("第%d个链表的值为:", i+1);
printList(&plist[i]);
}
return ;
}
```
这个程序可以在主函数中循环生成多个链表,并把每个链表存放在plist结构体数组中。用户可以输入链表数量和每个链表的节点数量和值,程序会自动创建链表并输出每个链表的值。