先遍历一遍知道有多长 然后取到中间把整个链表断开
然后把后半部分反转 并且一一merget到前部份
/*
* @lc app=leetcode id=143 lang=cpp
*
* [143] Reorder List
*
* https://leetcode.com/problems/reorder-list/description/
*
* algorithms
* Medium (29.57%)
* Total Accepted: 142K
* Total Submissions: 478.1K
* Testcase Example: '[1,2,3,4]'
*
* Given a singly linked list L: L0→L1→…→Ln-1→Ln,
* reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
*
* You may not modify the values in the list's nodes, only nodes itself may be
* changed.
*
* Example 1:
*
*
* Given 1->2->3->4, reorder it to 1->4->2->3.
*
* Example 2:
*
* *
* Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
*
*
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return;
}
int len = 1;
ListNode* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
len++;
}
//反转后半部分的链表然后加入到前半部分
temp = head;
int cnt = 1;
while (cnt != len / 2) {
temp = temp->next;
cnt++;
}
ListNode* H = new ListNode(0);
H->next = temp->next;
temp->next = nullptr;
// show2(head, H->next);
reverse(H);
merget(head, H->next);
//show2(head, H->next);
// show(H->next);
return;
}
void show2(ListNode* h1, ListNode* h2) {
show(h1);
cout << "\n";
show(h2);
}
void merget(ListNode* h1, ListNode* h2) {
while (h1->next != nullptr && h2->next != nullptr) {
ListNode *t1 = h1->next, *t2 = h2->next;
h1->next = h2;
h2->next = t1;
h2 = t2;
h1 = t1;
}
if (h1->next == nullptr) {
h1->next = h2;
}
}
void reverse(ListNode* H) {
//空的头节点和只有一个节点的情况
if (H->next == nullptr || H->next->next == nullptr) {
return;
}
ListNode *fast = H->next->next, *slow = H->next;
ListNode* t = fast;
while (fast != nullptr) {
t = t->next;
fast->next = slow;
slow = fast;
fast = t;
}
H->next->next = nullptr;
H->next = slow;
}
void show(ListNode* t) {
while (t != nullptr) {
cout << t->val << " ";
t = t->next;
}
cout << endl;
}
};