leetcode 之Reorder List(25)

 

 找到中间结点,将后半部分反转接入即可。

ListNode *reoderList(ListNode* head)
   {
       if (head == nullptr || head->next == nullptr)return head;
       //找到中间结点的方法很巧妙
       ListNode *slow = head, *fast = head,*prev=nullptr;
       while (fast&&fast->next)
       {
           prev = slow;
           slow = slow->next;
           fast = fast->next->next;
       }
       prev->next = nullptr;//从中间断开
       //将后半部分翻转
       slow = reverse(slow);
       //再将两段进行合并
       ListNode *curr = head;
       while (curr->next)
       {
           ListNode *tmp = curr->next;
           curr->next = slow;
           slow = slow->next;
           curr->next->next = tmp;
           curr = tmp;
       }

       curr->next = slow;

       return head;

   }
View Code

 

posted @ 2016-05-21 16:14  牧马人夏峥  阅读(128)  评论(0编辑  收藏  举报