Leetcoder Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.
class Solution {
public:
vector<void*> addr;
void reorderList(ListNode* head) {
if (head == NULL)return;
ListNode* begin = head;
//将所有的地址压入vector
while (begin != NULL)
{
addr.push_back(begin);
begin = begin->next;
}
//向量的 左右两边
int l = 1;
int r = addr.size() - 1;
ListNode* cur = head;
while (l < r)
{
cur->next = ((ListNode*)addr[r]);
cur = cur->next;
cur->next = ((ListNode*)addr[l]);
cur = cur->next;
l++;
r--;
}
if (l == r)
{
cur->next = ((ListNode*)addr[l]);
cur = cur->next;
}
cur->next = NULL;
}
};

浙公网安备 33010602011771号