143 Reorder List

Given a singly linked list L: L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.


解题思路

这本来是一道链表转换为另一个链表的题目。但是转换方式过于奇葩,实在不适合链表来做(链表更适合于做插入删除类的操做,或者是相邻元素之间的操作),于是果断决定先用个vector存起来,再进行转换。


代码

class Solution {
public:
    void reorderList(ListNode* head) {
        vector res;
        ListNode* s = head;
        while (s != NULL){
            res.push_back(s->val); s = s->next;
        }
        int l = 0, r = res.size()-1;
        ListNode* t = head;
        while (l <= r){
            t->val = res[l++];
            t = t->next;
            if (t == NULL) break;
            t->val = res[r--];
            t = t->next;
            if (t == NULL) break;
        }
    }
};

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