leetcode 143. 重排链表 medium
题目描述:
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解题思路:
寻找链表中点 + 链表逆序 + 合并链表
代码:
/**
* 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 reorderList(ListNode* head) {
if (!head || !head->next)
return;
// 1.快慢指针找到中点
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
}
// 2. 后半段 逆序
ListNode *head_1 = head;
ListNode *head_2 = slow->next;
slow->next = nullptr;
head_2 = reverse(head_2);
// 3. 后半段合并到前半段
ListNode *cur_1 = head_1, *cur_2 = head_2;
while (cur_1 && cur_2)
{
ListNode *tmp = cur_2->next;
cur_2->next = cur_1->next;
cur_1->next = cur_2;
cur_1 = cur_1->next->next;
cur_2 = tmp;
}
}
ListNode* reverse(ListNode* head)
{
ListNode *pre = nullptr, *cur = head, *back = nullptr;
while (cur)
{
back = cur->next;
cur->next = pre;
pre = cur;
cur = back;
}
return pre;
}
};