Posted on

Description

Submission

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        vector<ListNode*> v;

        for(ListNode* ptr = head; ptr; ptr = ptr->next) {
            v.push_back(ptr);
        }

        int n = v.size();

        vector<ListNode*> t;
        for(int i = 0, j = n - 1; i <= j; ++i, --j) {
            if(i == j) t.push_back(v[i]);
            else {
                t.push_back(v[i]);
                t.push_back(v[j]);
            }
        }

        t.push_back(nullptr);

        for(int i = 0; i < n; ++i) {
            t[i]->next = t[i+1];
        }
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *