Leetcode: Reorder List

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值