使用c语言定义一个链表且有两个递增有序的表A和B,其中A的容量大于A+B,请把A和B按序合并后放入A中,A和B若有重复元素,合并后只存一次,然后输出顺序表内容
时间: 2023-04-04 11:02:23 浏览: 93
我可以回答这个问题。以下是使用 C 语言定义一个链表且有两个递增有序的表 A 和 B,其中 A 的容量大于 A B,请把 A 和 B 按序合并后放入 A 中,A 和 B 若有重复元素,合并后只存一次,然后输出顺序表内容的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void insert(Node **head, int data) {
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}
Node *current = *head;
Node *prev = NULL;
while (current != NULL && current->data < data) {
prev = current;
current = current->next;
}
if (current == NULL) {
prev->next = new_node;
} else if (current->data > data) {
if (prev == NULL) {
new_node->next = *head;
*head = new_node;
} else {
prev->next = new_node;
new_node->next = current;
}
}
}
void merge(Node **a, Node *b) {
Node *current = b;
while (current != NULL) {
insert(a, current->data);
current = current->next;
}
}
void print_list(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *a = NULL;
Node *b = NULL;
insert(&a, 1);
insert(&a, 3);
insert(&a, 5);
insert(&a, 7);
insert(&a, 9);
insert(&b, 2);
insert(&b, 4);
insert(&b, 6);
insert(&b, 8);
merge(&a, b);
print_list(a);
return 0;
}
```
输出结果为:1 2 3 4 5 6 7 8 9
阅读全文