cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/831f8ab83843

时间限制:1秒 空间限制:32768K

题目描述

Given a singly linked list L: L 0L 1→…→L n-1L n,
reorder it to: L 0L nL 1L n-1L 2L n-2→…
You must do this in-place without altering the nodes' values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.

我的代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode *head) {
        if(head==nullptr || head->next==nullptr)
            return;
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast->next && fast->next->next){
            fast=fast->next->next;
            slow=slow->next;
        }
        ListNode* after=slow->next;
        slow->next=nullptr;//断开两个链表
        ListNode* pre=nullptr;
        while(after){
            //倒序后一个链表
            ListNode* next=after->next;
            after->next=pre;
            pre=after;
            after=next;
        }
        slow=head;
        while(slow&&pre){
            //合并两个链表
            ListNode* next=slow->next;
            ListNode* preNext=pre->next;
            pre->next=next;
            slow->next=pre;
            slow=next;
            pre=preNext;
        }
    }
};

运行时间:23ms
占用内存:1788k

posted on 2019-05-10 14:02  cherrychenlee  阅读(89)  评论(0编辑  收藏  举报