143. 重排链表
自己用vector模拟写的:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
ListNode *cur = head;
int len = 0;
while (cur)
{
++len;
cur = cur->next;
}
vector<ListNode *> v(len, nullptr);
cur = head;
int index = -1;
while (cur)
{
v[++index] = cur;
cur = cur->next;
}
for (int i = 0; i != len / 2; ++i)
{
v[i]->next = v[len - 1 - i];
v[len - 1 - i]->next = v[i + 1];
}
v[len / 2]->next = nullptr;
}
};
感觉是最笨的方法了,用vector把每个节点的地址存起来,再按需取用。