码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Reorder List

时间:2015-05-24 14:07:34      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:

Title:

思路:使用快慢指针,当快指针指向链表尾部时,将慢指针所指即以后反转,再将前后两个链表合并

class Solution {
public:
    void reorderList(ListNode* head) {
        ListNode*fast = head;
        ListNode*slow = head;
        while (fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* mid = slow;
       
        ListNode* tail = NULL;
        while (slow){
            ListNode* t = slow->next;
            slow->next = tail;
            tail = slow;
            slow = t;
        }
        fast = head;
        ListNode* head1 = new ListNode(0);
        ListNode* p = head1;
        while (fast != mid && tail){
            p->next = fast;
            p = fast;
            fast = fast->next;
            p->next = tail;
            p = tail;
            tail = tail->next;
        }
        if (tail){
            p->next = tail;
        }
        head = head1->next;
    }
};

 

LeetCode: Reorder List

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4525754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!