143. Reorder List

143. Reorder List_第1张图片
image.png

找到中点,右半部分翻转,两段合并

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(head == NULL || head->next == NULL) return;
        ListNode *middle = findMiddle(head);
        ListNode *pRight = middle->next;
        middle->next = NULL;
        cout<<"p"<val<next, *p = head;
        cout<val<next = newpRight;
            newpRight = newpRight->next;
            p = p->next;
            p->next = cur;
            cur = cur->next;
            p = p->next;
        }
        if(cur){
            p->next = cur;
        }
        if(newpRight){
            p->next = newpRight;
        }
    }
private:
    ListNode * findMiddle(ListNode * head){
        ListNode *slow = head, *fast = head->next;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
        }
        return  slow;
    }
    ListNode * reverseList(ListNode *head){
        ListNode *prev = NULL, * cur = head;
        while(cur){
            ListNode *tmp = cur->next;
            cur->next = prev;
            prev = cur;
            cur = tmp;
        }
        return prev;
    }
};

你可能感兴趣的:(143. Reorder List)