Leetcode 143 重排链表

给定一个单链表 LL0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→LnL1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
/**
 * 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) {}
 * };
 */
//先通过快慢指针找到中间节点 也就是slow最后停的位置
//再将后半段 逆置
//再依次将后半段插入到前半段
class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head || !head->next) return ;
        ListNode* slow = head, * fast = head, * slow_pre = head;
        // //先通过快慢指针找到后半段的首结点 也就是slow最后停的位置
        while (fast->next)
        {
            slow_pre = slow;
            slow = slow->next;
            fast = fast->next;
            if (fast->next)fast = fast->next;
        }
        ListNode* temp_head = new ListNode(0, NULL);//临时头结点
        ListNode* p = slow,*next_node=NULL,*q=NULL;
        slow_pre->next = NULL;
        //再将后半段 逆置
        while (p)
        {
            next_node = p->next;
            p->next = temp_head->next;
            temp_head->next = p;
            p = next_node;
        }
        p = head;
        q = temp_head->next;
        delete(temp_head);
        //再依次将后半段逐个插入到前半段
        while (p)
        {
            next_node = q->next;
            q->next = p->next;
            p->next = q;
            q = next_node;
            if (p->next->next)
                p = p->next->next;
            else
            {
                p->next->next = next_node;
                break;
            } 
        }
    }
};
原文地址:https://www.cnblogs.com/lancelee98/p/13224050.html