zoukankan      html  css  js  c++  java
  • LeetCode-Reorder List

    Given a singly linked list L: L0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-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) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(head==NULL)return;
            if(head->next==NULL)return;
            int count=0;
            ListNode* ptr=head;
            while(ptr!=NULL){
                count++;
                ptr=ptr->next;
            }
            int len;
            if(count%2==0)len=count/2;
            else len=count/2+1;
            ptr=head;
            for(int i=0;i<len-1;i++)ptr=ptr->next;
            ListNode* tmp;
            ListNode* ptr2=ptr->next;
            ptr->next=NULL;
            ptr=ptr2;
            ptr2=ptr->next;
            while(ptr2!=NULL){
                tmp=ptr2->next;
                ptr2->next=ptr;
                ptr=ptr2;
                ptr2=tmp;
            }
            ptr2=head;
            len=count/2;
            for(int i=0;i<len;i++){
                tmp=ptr2->next;
                ptr2->next=ptr;
                ptr2=tmp;
                tmp=ptr->next;
                ptr->next=ptr2;
                ptr=tmp;
            }
        }
    };
  • 相关阅读:
    CF1051F The Shortest Statement
    [ZJOI2006]书架
    [FJOI2007]轮状病毒
    CF147B Smile House
    HDU4415 Assassin’s Creed
    飞行员配对方案问题
    [NOI2005]瑰丽华尔兹
    [NOIP2016]换教室
    [国家集训队]部落战争
    [NOI2005]聪聪与可可
  • 原文地址:https://www.cnblogs.com/superzrx/p/3420915.html
Copyright © 2011-2022 走看看