A recursion method. In each recursion, suppose # i to # j is already sorted. Return the pair of # i and # j+1
This can reduce the time to find next order node compared to brute force method.
struct ListNodePair {
ListNode *head;
ListNode *tail;
ListNodePair(ListNode *p, ListNode *q) :
head(p), tail(q) {}
};
class Solution3 {
public:ListNodePair recurList(ListNode *head, int len) {
// Use recursion, return the current head and tail in last recursion
// The idea is divide and conquer to reduce the time need to find next tail
if (len <= 2) {
ListNode *tail = head;
while (len--) // A tricky place
tail = tail->next;
return ListNodePair(head, tail);
}
ListNodePair pair = recurList(head->next, len-2);
// The returned tail should be the next of previous tail
ListNodePair retPair(head, pair.tail->next);
head->next = pair.tail;
pair.tail->next = pair.head;
return retPair;
}
void reorderList(ListNode *head) {
// AC in 328ms
// I like this code better than Solution4, although use a struct, return two pointers
// The structures and function definition is very clear and clean
if (head == NULL)
return;
int len;
ListNode *p;
for (p = head, len = 0; p != NULL; p = p->next, len++);
recurList(head, len);
for (p = head; len > 1; p = p->next, len--);
p->next = NULL;
}
};