思路:
链表操作的基本操作。属于经典基础题型。
时间复杂度O(N),空间复杂度O(1)。
先找到中间节点,然后后半段反转,再插入到前半段中。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* reverse(ListNode *head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *prev = head;
for(ListNode *cur = head->next, *next = cur->next; cur; prev = cur, cur = next, next = next ? next->next : nullptr) {
cur->next = prev;
}
head->next = nullptr;
return prev;
}
public:
void reorderList(ListNode* head) {
if(head == nullptr || head->next == nullptr || head->next->next == nullptr) return;
//find the mid node
ListNode *slow = head, *fast = head, *prev = nullptr;
while(fast != nullptr && fast->next != nullptr) {
prev = slow;
slow = slow->next;
fast= fast->next->next;
}
prev->next = nullptr;
//reverse the latter
ListNode *latter = reverse(slow);
//insert
ListNode *cur = head;
while(cur->next != nullptr) {
ListNode *tmp = cur->next;
cur->next = latter;
latter = latter->next;
cur->next->next = tmp;
cur = tmp;
}
cur->next = latter;
}
};