143. 重排链表——寻找链表中点 + 链表逆序 + 合并链表

class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head || !head -> next || ! head -> next -> next)    //长度小于2都不用处理
            return;
        ListNode *slow = head, *fast = head, *sec;
        while(fast && fast -> next){    //快慢指针找到中间的节点
            slow = slow -> next;
            fast = fast -> next -> next;
        }
        fast = slow -> next;    //fast标记为下一段
        slow -> next = nullptr; //截断
        reverseList(fast);  //第二段反序
        combineList(head, fast);    //合并
    }
    void reverseList(ListNode*& head){
        ListNode *left = head, *mid = head -> next, *right;
        while(mid){
            right = mid -> next;    //right向右移动
            left -> next = right;   //left指向下一个点
            mid -> next = head;     //mid向左指
            head = mid; //head记录头节点,也就是每一次中较右的节点
            mid = right;    //mid向右移动
        }
    }

    void combineList(ListNode*& fir, ListNode*& sec){
        while(sec){ //默认fir长1个单位 或 长度相等
            ListNode *temp = sec;
            sec = sec -> next;
            //插入节点
            temp -> next = fir -> next;
            fir -> next = temp;
            fir = temp -> next;
        }
    }
};

Accepted
12/12 cases passed (28 ms)
Your runtime beats 96.76 % of cpp submissions
Your memory usage beats 69.4 % of cpp submissions (17.3 MB)

你可能感兴趣的:(力扣每日刷题,链表,数据结构,算法,c++,leetcode)