/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
12345
1, 找到中间点mid
2,链表分成两份,l1 = 12345, l2 = 34(mid->next)
mid->next = nullptr
所以:l1 = 123, l2 = 45
2,翻转l2
3, l1和l2拼接。
Q:为什么翻转l2一定会翻转自身。
*/
class Solution {
public:
// 为什么getNum不影响,reverse会影响
ListNode *reverse(ListNode *root) {
if (!root) {
return root;
}
ListNode *pre = nullptr;
ListNode *curr = root;
while(curr) {
ListNode *next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
}
return pre;
}
ListNode *getMid (ListNode *head) {
ListNode *slow = head, *fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
void mergeList(ListNode *l1, ListNode *l2) {
ListNode *l1_tmp;
ListNode *l2_tmp;
while (l1 != nullptr && l2 != nullptr) {
l1_tmp = l1->next;
l2_tmp = l2->next;
l1->next = l2;
l1 = l1_tmp;
l2->next = l1;
l2 = l2_tmp;
}
}
void reorderList(ListNode *head) {
if (!head) {
return;
}
ListNode *mid = getMid(head);
ListNode *l1 = head;
ListNode *l2 = mid->next;
mid->next = nullptr;
ListNode *l2Reverse = reverse(l2);
mergeList(l1, l2Reverse);
}
};