题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head node * @return ListNode类 */ #include <stdlib.h> int compare(const void* a,const void *b){ return ((struct ListNode*)a)->val-((struct ListNode*)b)->val; } struct ListNode* sortInList(struct ListNode* head ) { // write code here struct ListNode* p=head; int i=0; while(p!=NULL){ p=p->next; i++; } p=head; int arr[i],n=0; while(p!=NULL){ arr[n]=p->val; p=p->next; n++; } qsort(arr, i, sizeof(arr[0]), compare); p=head; n=0; while(p!=NULL){ p->val=arr[n]; n++; p=p->next; } return head; }