首页 > 其他 > 详细

LeetCode: Reorder List

时间:2015-05-24 14:04:42      阅读:212      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!