c语言合并两个递增链表为一个单调递增链表用数组
时间: 2024-03-13 12:38:51 浏览: 109
C语言合并两个带头节点升序排列链表
以下是C语言合并两个递增链表为一个单调递增链表的代码,使用数组实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int arr[], int n) {
Node *head = NULL, *p = NULL;
for (int i = 0; i < n; i++) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
p = head;
} else {
p->next = node;
p = p->next;
}
}
return head;
}
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
Node *mergeList(Node *head1, Node *head2) {
int arr[MAX_SIZE];
int i = 0;
Node *p1 = head1, *p2 = head2;
while (p1 != NULL && p2 != NULL) {
if (p1->data < p2->data) {
arr[i++] = p1->data;
p1 = p1->next;
} else {
arr[i++] = p2->data;
p2 = p2->next;
}
}
while (p1 != NULL) {
arr[i++] = p1->data;
p1 = p1->next;
}
while (p2 != NULL) {
arr[i++] = p2->data;
p2 = p2->next;
}
Node *head = createList(arr, i);
return head;
}
int main() {
int arr1[] = {1, 3, 5, 7, 9};
int arr2[] = {2, 4, 6, 8, 10};
Node *head1 = createList(arr1, 5);
Node *head2 = createList(arr2, 5);
Node *head = mergeList(head1, head2);
printList(head);
return 0;
}
```
阅读全文