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

143. Reorder List

时间:2017-04-04 12:52:34      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:next   bsp   amp   alter   solution   alt   fas   str   中间   

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-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||!head->next)return ;
        ListNode* fast=head,*slow=head;
        //找到中间结点
        while(fast->next&&fast->next->next){
            fast=fast->next->next;
            slow=slow->next;
        }
        //反转后半部分
        slow=reverse(slow->next);
        //交叉插入,得到结果
        fast=head;
        while(slow){
            ListNode* slowNext=slow->next;
            slow->next=fast->next;
            fast->next=slow;
            fast=slow->next;
            slow=slowNext;
        }
        //最后置空,否则会使得链表永不停息。
        fast->next=NULL;
    }
    ListNode* reverse(ListNode* head){
        ListNode* p=head->next,*next;
        head->next=NULL;
        while(p){
            next=p->next;
            p->next=head;
            head=p;
            p=next;
        }
        return head;
    }
};

 

143. Reorder List

标签:next   bsp   amp   alter   solution   alt   fas   str   中间   

原文地址:http://www.cnblogs.com/tsunami-lj/p/6664558.html

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