Beispiel #1
0
 void sortListHelper(ListNode* head, ListNode* tail) {
     if (head -> next == tail) return;
     /* Partition the list. */
     ListNode* pre = head;
     ListNode* cur = head -> next;
     ListNode* pivot = cur;
     while (cur -> next && cur -> next != tail) {
         if (pivot -> val > cur -> next -> val) {
             ListNode* temp = pre -> next;
             pre -> next = cur -> next;
             cur -> next = cur -> next -> next;
             pre -> next -> next = temp;
         }
         else cur = cur -> next;
     }
     sortListHelper(head, pivot);
     /* Here is the trick. */
     while (pivot -> next != tail && pivot -> next -> val == pivot -> val)
         pivot = pivot -> next;
     if (pivot -> next != tail) sortListHelper(pivot, tail);
 }
Beispiel #2
0
ListNode *sortList2(ListNode *head) {
    ListNode *saved_head = head;
    int count = 0,step;
    int length = 1;
    while ((head = head->next)) length++;
    while (true) {
        step = pow(2, count);
        if (step >= length) break;
        sortListHelper(&saved_head,step);
        count++;
    }
    return saved_head;
}
Beispiel #3
0
 ListNode* sortList(ListNode* head) {
     ListNode* new_head = new ListNode(0);
     new_head -> next = head;
     sortListHelper(new_head, NULL);
     return new_head -> next;
 }