用c++将一个数组转换成一个链表,并使其有序
时间: 2023-05-15 13:05:31 浏览: 83
可以使用以下代码将一个数组转换成一个有序链表:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createNode(int val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
struct ListNode* arrayToList(int* nums, int size) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
for (int i = 0; i < size; i++) {
struct ListNode* node = createNode(nums[i]);
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int cmp(const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
struct ListNode* arrayToSortedList(int* nums, int size) {
qsort(nums, size, sizeof(int), cmp);
return arrayToList(nums, size);
}
int main() {
int nums[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int size = sizeof(nums) / sizeof(nums[0]);
struct ListNode* head = arrayToSortedList(nums, size);
printList(head);
return 0;
}
```
这段代码将一个数组转换成一个有序链表,并输出链表中的元素。