【reorder-list】

来源:互联网 发布:百元电脑音箱推荐 知乎 编辑:程序博客网 时间:2024/06/08 19:40

Given a singly linked list LL 0L 1→…→L n-1L n,
reorder it to: L 0L n L 1L n-1L2L n-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中,然后能被2整除的,节点存放v[i]位置

不能被二整除的存放最后的节点。

class Solution{public:void reorderList(ListNode* head){if (head==NULL || head->next==NULL){return;}vector<int> v;ListNode* p = head;while (p){v.push_back(p->val);p = p->next;}int j = v.size() - 1;int i = 0;int index = 0;p = head;while (i<=j){if (index%2==0){p->val = v[i];i++;}else{p->val = v[j];j--;}index++;p = p->next;}}};


原创粉丝点击