143 Reorder List

Given a singly linked list L: <i>L</i>: <i>L</i>0→<i>L</i>1→…→<i>L</i><i>n</i>-1→<i>L</i>n,
reorder it to: <i>L</i>0→<i>L</i><i>n</i>→<i>L</i>1→<i>L</i><i>n</i>-1→<i>L</i>2→<i>L</i><i>n</i>-2→…

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

For example,
Given <code>{1,2,3,4}</code>, reorder it to <code>{1,4,2,3}</code>.


解题思路

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


代码

class Solution {
public:
    void reorderList(ListNode* head) {
        vector<int> 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;
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容