题目:
代码(首刷自解 2024年4月11日):
class Solution {
public:
void reorderList(ListNode* head) {
if (!head) return;
// 用一个hash存储下表对应的节点
unordered_map<int, ListNode*> index_to_node;
ListNode* cur = head;
int index = 0;
while(cur) {
index_to_node[index++] = cur;
cur = cur->next;
}
// 根据下表重排链表
int i, j;
for (i = 0, j = index - 1; i < j; ) {
index_to_node[i++]->next = index_to_node[j];
if (i >= j) break;
index_to_node[j--]->next = index_to_node[i];
}
index_to_node[i]->next = nullptr;//很重要,循环结束要置空,不然会循环链表
}
};
代码(二刷看解析 2024年8月6日)
看的林茶山大佬的
class Solution {
private:
ListNode* mid(ListNode* head) {
auto fast = head;
auto slow = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode* reverseNode(ListNode* head) {
ListNode* pre = nullptr;
auto cur = head;
while (cur) {
auto nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
public:
void reorderList(ListNode* head) {
auto midNode = mid(head);
auto head2 = reverseNode(midNode);
while (head2->next) {
auto nxt = head->next;
auto nxt2 = head2->next;
head->next = head2;
head2->next = nxt;
head = nxt;
head2 = nxt2;
}
}
};