LeeCode 143. 重排链表
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:

输入:head = [1,2,3,4] 输出:[1,4,2,3]
示例 2:

输入:head = [1,2,3,4,5] 输出:[1,5,2,4,3]
提示:
- 链表的长度范围为
[1, 5 * 104] 1 <= node.val <= 1000
答案&测试代码:
void testLeeCode143() { // LeeCode 143.重排链表struct ListNode {int val;ListNode *next;ListNode() : val(0), next(nullptr) {}ListNode(int x) : val(x), next(nullptr) {}ListNode(int x, ListNode *next) : val(x), next(next) {}};class Solution {public:void reorderList(ListNode* head) { // LeeCode 143.重排链表if (!head) return;if (!(head->next)) return;vector<ListNode*> vec;for (ListNode *p = head; p;) {vec.emplace_back(p);ListNode *next = p->next;p->next = nullptr;p = next;}head = vec[0];vec.erase(vec.begin() + 0); // 删除指定索引处元素head->next = vec.back(); // 获取最后一个元素vec.erase(vec.begin() + vec.size() - 1);ListNode *last = head->next;for (;vec.size() > 0;) {ListNode *first = vec[0];last->next = first;last = first;vec.erase(vec.begin() + 0);if (vec.size() > 0) {ListNode *back = vec.back();last->next = back;last = back;vec.erase(vec.begin() + vec.size() - 1);}}}};// 测试代码:ListNode node1 = ListNode(1);ListNode node2 = ListNode(2);ListNode node3 = ListNode(3);ListNode node4 = ListNode(4);node1.next = &node2;node2.next = &node3;node3.next = &node4;Solution solution;solution.reorderList(&node1);// 打印链表std::cout << "链表:";for (ListNode *p = &node1; p; p = p->next) {std::cout << p->val << " ";}std::cout << endl;
}
打印:

ok. 提交到LeeCode:

ok.
