题目描述
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
链接:https://leetcode-cn.com/problems/reorder-list
示例1
解题思路
为了减少空间复杂度,我们可以这样来做,由题目来看我们先把链表分成两半,然后对后一半进行逆序,最后再逐个插入到第一个链表即可:
/*** 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:ListNode* find_mid(ListNode* head) {// 确保链表至少有两个节点ListNode* fast = head;ListNode* slow = new ListNode(-1);slow->next = head;while (fast && fast->next) {slow = slow->next;fast = fast->next->next;}return slow;}ListNode* reverse_list(ListNode* head) {ListNode* pre_node = NULL;ListNode* curr = head;while (curr) {ListNode* temp = curr->next;curr->next = pre_node;pre_node = curr;curr = temp;}return pre_node;}void reorderList(ListNode* head) {ListNode* mid_node = find_mid(head);if (mid_node->val == -1)return;ListNode* half_front = head;ListNode* half_back = mid_node->next;mid_node->next = NULL;half_back = reverse_list(half_back);ListNode* curr = new ListNode();ListNode* ret = new ListNode();ret->next = curr;while (half_front || half_back) {if (half_front) {curr->next = half_front;half_front = half_front->next;curr = curr->next;}if (half_back) {curr->next = half_back;half_back = half_back->next;curr = curr->next;}}head = ret->next;}};
