单链表排序c语言代码
时间: 2023-10-22 22:09:09 浏览: 138
单链表的排序,c源代码
4星 · 用户满意度95%
以下是单链表排序的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* insertionSortList(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode *cur = head->next, *pre = head;
while (cur != NULL) {
if (cur->val >= pre->val) {
pre = cur;
cur = cur->next;
} else {
pre->next = cur->next;
struct ListNode *p = dummy;
while (p->next->val < cur->val) {
p = p->next;
}
cur->next = p->next;
p->next = cur;
cur = pre->next;
}
}
return dummy->next;
}
int main() {
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
head->val = 4;
head->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->next->val = 1;
head->next->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->next->next->val = 3;
head->next->next->next->next = NULL;
struct ListNode *sortedList = insertionSortList(head);
while (sortedList != NULL) {
printf("%d ", sortedList->val);
sortedList = sortedList->next;
}
printf("\n");
return 0;
}
```
阅读全文