C语言利用函数传递两个结构体指针,用其中一个指针遍历该指针指向的链表,对满足条件的,在该函数里再利用另一个函数以二级指针作为参数实现对另一个指针指向的链表删除,插入操作
时间: 2024-02-12 19:05:53 浏览: 30
好的,我来解答你的问题。
首先,我们需要定义两个结构体,用来表示链表中的节点和节点中的数据:
```c
struct Node {
int data;
struct Node *next;
};
struct Data {
int id;
char name[20];
int age;
};
```
然后,我们需要写两个函数,一个用来遍历链表并对满足条件的节点进行删除操作,另一个用来对指定节点进行插入操作。
```c
void delete_node(struct Node **head, int target) {
struct Node *curr = *head;
struct Node *prev = NULL;
while (curr != NULL) {
if (curr->data == target) {
if (prev == NULL) {
*head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
return;
}
prev = curr;
curr = curr->next;
}
}
void insert_node(struct Node **head, struct Data *data) {
struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data->id;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
} else {
struct Node *curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = new_node;
}
}
```
最后,我们需要一个主函数来调用这两个函数,实现对链表的操作。
```c
int main() {
struct Node *head1 = NULL; // 第一个链表
struct Node *head2 = NULL; // 第二个链表
// 假设链表1和链表2分别包含以下数据
struct Data data1[] = {{1, "Tom", 20}, {2, "Jerry", 19}, {3, "Mike", 21}};
struct Data data2[] = {{4, "John", 22}, {5, "Alice", 20}, {6, "Bob", 23}};
// 将数据插入到链表1中
for (int i = 0; i < 3; i++) {
insert_node(&head1, &data1[i]);
}
// 遍历链表1,对满足条件的节点进行删除操作,并将数据插入到链表2中
struct Node *curr = head1;
while (curr != NULL) {
if (curr->data % 2 == 0) {
delete_node(&head1, curr->data);
insert_node(&head2, &data2[curr->data % 3]);
}
curr = curr->next;
}
// 输出链表1和链表2中的数据
curr = head1;
printf("链表1中的数据:");
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
curr = head2;
printf("链表2中的数据:");
while (curr != NULL) {
printf("(%d, %s, %d) ", data2[curr->data % 3].id, data2[curr->data % 3].name, data2[curr->data % 3].age);
curr = curr->next;
}
printf("\n");
return 0;
}
```
希望我的回答能够帮助到你!