没想到什么好办法,要将O(ologn)时间里完成,我先遍历一遍将链表存储到数组里,再对数组进行排序,排序方法写了快排和归并的,过是能过,但是时间要140ms,最快的就是直接对链表进行归并排序,第一次写比较难受,用快慢指针来分成两个链表,具体思想还是和数组的归并排序一样。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void merge(int A[],int L1,int R1,int L2,int R2){
int i = L1, j = R2; // i指向A[L1] j指向A[L2]
int temp[100000], Index = 0;
while (i <= R1 && j<=R2) {
if (A[i] <= A[j])
temp[Index++] = A[i++];
else
temp[Index++] = A[j++];
}
while (i <= R1) temp[Index++] = A[i++];
while (j <= R2) temp[Index++] = A[j++];
for (int i =0; i<Index; i++)
A[L1 + i] = temp[i];
}
void merge_sort(int A[],int left,int right){
if (left < right){
int mid = (left+right) / 2;
merge_sort(A, left, mid);
merge_sort(A, mid+1, right);
merge(A, left, mid,mid+1,right);
}
}
int Partition(int A[],int left,int right){
int temp = A[left];
while (left < right) {
while (left < right && A[right] > temp)
right--;
A[left] = A[right];
while (left <right && A[left] <= temp)
left++;
A[right] = A[left];
}
A[left] = temp;
return left;
}
void quick_sort(int A[],int left,int right){
if (left < right) {
int pos = Partition(A, left, right);
quick_sort(A, left, pos-1);
quick_sort(A, pos+1, right);
}
}
struct ListNode* sortList(struct ListNode* head) {
if(!head || !head->next)
return head;
int data[100000];
int index = 0; // the length of the list
struct ListNode *current = head;
while(current){
data[index++] = current->val;
current = current->next;
}
quick_sort(data,0,index-1);
current = head;
index = 0;
while(current){
current->val = data[index++];
current = current->next;
}
return head;
}