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

[Linked List]Reorder List

时间:2015-12-12 21:43:22      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

otal Accepted: 54991 Total Submissions: 252600 Difficulty: Medium

 

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:
    ListNode* reverseList(ListNode* head)
    {
        ListNode* cur     = head;
        ListNode* newHead = NULL;
        ListNode* next    = NULL;
        while(cur){
            next = cur->next;
            cur->next = newHead;
            newHead = cur;
            cur = next;
        }
        return newHead;
    }
    
    void reorderList(ListNode* head) 
    {
        if(head==NULL || head->next==NULL){
            return;
        }
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* pre  = NULL;
        while(fast){
            pre = slow;
            slow = slow->next;
            fast->next ? fast = fast->next->next : fast = NULL;
        }
        pre->next = NULL;
        ListNode* head2 = reverseList(slow);
        
        ListNode* cur       = head;
        ListNode* cur_next  = NULL;
        ListNode* cur2      = head2;
        ListNode* cur2_next = NULL;
        while(cur2){
            cur_next  = cur->next;
            cur2_next = cur2->next;
            
            cur->next  = cur2;
            cur2->next = cur_next;
            
            cur  = cur_next;
            cur2 = cur2_next;
        }
    }
};

[Linked List]Reorder List

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5041732.html

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