一、题目
二、题解
找到中间节点,从中间断开后将后部分逆转,然后合并两个链表
/**
* Definition for singly-linked list.
* 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 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 == nullptr || head->next == nullptr) return;
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr && fast->next->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* cur = slow->next;
slow->next = nullptr;
slow = cur->next;
cur->next = nullptr;
while (slow != nullptr) {
ListNode* next = slow->next;
slow->next = cur;
cur = slow;
slow = next;
}
mergeList(head, cur);
}
};