My C++ solution


  • 0
    class Solution {
    public:
        void reorderList(ListNode* head) {
            if (!head || !head->next || !head->next->next) return;
    		int len = 0;
    		ListNode *temp = head;
    		while (temp){ ++len; temp = temp->next; }
    		int pos = (len - 1) / 2;
    		vector<ListNode*> vp(pos);
    		int num = len % 2 ? pos : pos + 1;
    		temp = head;
    		for (int i = 0; i < num; i++)	temp = temp->next;
    		for (int i = 0; i < pos; i++){
    			vp[i] = temp->next;
    			temp->next = nullptr;
    			temp = vp[i];
    		}
    		temp = head;
    		for (int i = pos - 1; i >= 0; i--){
    			ListNode* tp = temp->next;
    			vp[i]->next = temp->next;
    			temp->next = vp[i];
    			temp = tp;
    		}
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.