143 重排链表

方法一 活用set

void reorderList(ListNode *head) {
    if (head == nullptr || head->next == nullptr)
        return;
    set<ListNode *> save;
    int len = 1;
    ListNode *t = head;
    for (; t->next != nullptr; t = t->next)
        ++len;
    int mid = len % 2 == 0 ? len / 2 : (len + 1) / 2;
    t = head;
    for (; mid > 0; --mid)
        t = t->next;
    while (t != nullptr) {
        save.insert(t);
        t = t->next;
    }
    t = head;
    auto end = --save.end();
    for (auto size = save.size(); size > 0; --size) {
        (*end)->next = t->next;
        t->next = *end;
        t = t->next->next;
        --end;
    }
    t->next = nullptr;
}

方法二 快慢指针找中点然后反转后半部分链表,然后插入到前半个链表当中去

ListNode *reverse(ListNode *head) {
    ListNode *front = head, *rear = nullptr, *temp = nullptr;
    while (front != nullptr) {
        temp = front->next;
        front->next = rear;
        rear = front;
        front = temp;
    }
    return rear;
}

void reorderList(ListNode *head) {
        if(head== nullptr||head->next== nullptr)
        return;
    auto *prehead = new ListNode(0);
    prehead->next = head;
    ListNode *fast = prehead, *slow = prehead;
    while (fast->next != nullptr) {
        fast = fast->next;
        slow = slow->next;
        if (fast->next == nullptr)
            break;
        fast = fast->next;
    }
    slow = reverse(slow->next);
    fast = head;
    while (slow != nullptr) {
        ListNode *temp = slow->next;
        slow->next = fast->next;
        fast->next = slow;
        slow = temp;
        fast = fast->next->next;
    }
    fast->next = nullptr;
}
原文地址:https://www.cnblogs.com/INnoVationv2/p/10260229.html