Problem:
Sort a linked list in O (n log n) time using constant space complexity.
Solution:
First, the time complexity can reach the O (nlgn) sorting algorithm. There are three common types: heap sorting, Merge Sorting, and quick sorting,
For linked lists, sorting by heap is obviously unlikely. Therefore, we can merge them or sort them quickly. Because we merge two linked lists, we only use
Modify the corresponding pointer, so it can achieve space complexity O (1). The following is the sort of linked lists using the merge sort idea.
Solution:
Class solution {public: listnode * sortlist (listnode * P) {If (P = NULL | p-> next = NULL) return P; // Add a header node, avoid the case where rear is empty during merging. listnode * head = new listnode (-1), * q = head; head-> next = P; int CNT = 0; while (p) {++ CNT; P = p-> next; If (CNT % 2 = 0) q = Q-> next;} p = Q-> next, Q-> next = NULL; // recursively sort the left and right sides of the head-> next = q = sortlist (Head-> next); P = sortlist (p); // merge q = merge (Head, p); free (head); Return Q;} listnode * Merge (listnode * head, listnode * r) {listnode * l = head-> next, * rear = head; while (L & R) {If (L-> Val <r-> Val) {rear-> next = L; L = L-> next, rear = rear-> next;} else {rear-> next = r; r = r-> next, rear = rear-> next;} while (l) {rear-> next = L; L = L-> next, rear = rear-> next;} while (r) {rear-> next = R; R = r-> next, rear = rear-> next;} return head-> next ;}};