用c语言链表实现A={7,5,3,11}何B={2,6,3}和并}
时间: 2023-10-23 14:08:42 浏览: 26
以下是用C语言链表实现A={7,5,3,11}和B={2,6,3}合并的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
Node* mergeLists(Node* list1, Node* list2) {
Node* head = NULL;
Node* tail = NULL;
while (list1 != NULL && list2 != NULL) {
if (list1->data < list2->data) {
if (head == NULL) {
head = list1;
tail = head;
} else {
tail->next = list1;
tail = tail->next;
}
list1 = list1->next;
} else {
if (head == NULL) {
head = list2;
tail = head;
} else {
tail->next = list2;
tail = tail->next;
}
list2 = list2->next;
}
}
if (list1 != NULL) {
if (head == NULL) {
head = list1;
} else {
tail->next = list1;
}
}
if (list2 != NULL) {
if (head == NULL) {
head = list2;
} else {
tail->next = list2;
}
}
return head;
}
int main() {
Node* A = createNode(7);
A->next = createNode(5);
A->next->next = createNode(3);
A->next->next->next = createNode(11);
Node* B = createNode(2);
B->next = createNode(6);
B->next->next = createNode(3);
printf("A: ");
printList(A);
printf("B: ");
printList(B);
Node* mergedList = mergeLists(A, B);
printf("Merged list: ");
printList(mergedList);
return 0;
}
```
输出:
```
A: 7 5 3 11
B: 2 6 3
Merged list: 2 6 3 7 5 3 11
```