用c语言写一个传入头节点后,把单链表节点按字符数组首字母的字母表顺序排序后,返回这个链表的头节点
时间: 2023-04-06 21:02:59 浏览: 68
好的,这是一个关于编程的问题,我可以回答。以下是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode {
char* str;
struct ListNode* next;
};
int compare(char* str1, char* str2) {
return strcmp(str1, str2) < 0;
}
struct ListNode* sortList(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* mid = head;
struct ListNode* tail = head;
while (tail->next != NULL && tail->next->next != NULL) {
mid = mid->next;
tail = tail->next->next;
}
struct ListNode* head2 = mid->next;
mid->next = NULL;
struct ListNode* head1 = sortList(head);
head2 = sortList(head2);
struct ListNode dummy;
struct ListNode* tail1 = &dummy;
while (head1 != NULL && head2 != NULL) {
if (compare(head1->str, head2->str)) {
tail1->next = head1;
head1 = head1->next;
} else {
tail1->next = head2;
head2 = head2->next;
}
tail1 = tail1->next;
}
if (head1 != NULL) {
tail1->next = head1;
} else {
tail1->next = head2;
}
return dummy.next;
}
int main() {
struct ListNode* head = NULL;
char* strs[] = {"hello", "world", "apple", "banana", "cat", "dog"};
int n = sizeof(strs) / sizeof(strs[0]);
for (int i = 0; i < n; i++) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->str = strs[i];
node->next = head;
head = node;
}
head = sortList(head);
while (head != NULL) {
printf("%s ", head->str);
head = head->next;
}
printf("\n");
return 0;
}
```
这个程序可以将一个单链表按照字符数组首字母的字母表顺序排序,并返回排序后的链表的头节点。