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;
            }
        }
    };
  • 相关阅读:
    Python 初识爬虫-**机场出港业务
    Python 基础学习之字典
    Python 基础学习之if语句
    初识 超级账本
    搭建element-ui Vue结构
    回归
    Gin框架body参数获取
    log4go折腾
    go获取当前执行的位置程序
    mybatis generator 整合lombok
  • 原文地址:https://www.cnblogs.com/superzrx/p/3420915.html
Copyright © 2011-2022 走看看