LCR 026. 重排链表
题目链接:LCR 026. 重排链表
注:该题与 143. 重排链表完全一样
代码如下:
            
            
              cpp
              
              
            
          
          class Solution {
public:
    void reorderList(ListNode* head)
    {
        if(head==nullptr||head->next==nullptr||head->next->next==nullptr)
            return;
        ListNode* Head=new ListNode;
        Head->next=nullptr;
        ListNode* r=head;
        //找到中间节点
        ListNode* slow=head,*fast=head,*slow_pre=nullptr;
        while(fast)
        {
            slow_pre=slow;
            slow=slow->next;
            fast=fast->next;
            if(fast)
                fast=fast->next;
        }
        slow_pre->next=nullptr;//前后链表进行断开操作
        //后半段进行逆置操作
        ListNode* afterLinkHead=new ListNode;
        afterLinkHead->next=nullptr;
        while(slow)
        {
            ListNode* temp=slow;
            slow=slow->next;
            temp->next=afterLinkHead->next;
            afterLinkHead->next=temp;
        }
        fast=head;
        slow=afterLinkHead->next;
        int count=0;
        while(fast&&slow)//轮流进行重新插入
        {
            ListNode* temp=nullptr;
            if(count%2==0)
            {
                temp=fast;
                fast=fast->next;
            }else
            {
                temp=slow;
                slow=slow->next;
            }
            temp->next=nullptr;
            r->next=temp;
            r=temp;
            count++;
        }
        while(fast)//把剩余的节点进行插入
        {
            ListNode* temp=fast;
            fast=fast->next;
            temp->next=nullptr;
            r->next=temp;
            r=temp;
        }
        while(slow)//把剩余的节点进行插入
        {
            ListNode* temp=slow;
            slow=slow->next;
            temp->next=nullptr;
            r->next=temp;
            r=temp;
        }
        head=Head->next;
    }
};