Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L2→L 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;
}
}
};