zoukankan      html  css  js  c++  java
  • Reorder List 微软笔试题

    Given a singly linked list LL0L1→…→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}

    现在在Leetcode上也有了,这题的做法有很多,我是用的是一个舍友给我提供的一种方法,先把后面部分反转在重新插入即可。

    /**
     * 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.
            int length;
            length = 0;
            ListNode *p,*q,*t;
            p = head;
            while(p)
            {
                p = p->next;
                length++;
            }
            if(length<=2)
            return ;
            p = head;
            length = length/2;
            for(int i = 0;i<length;i++)
            {
                p = p->next;
            }
            t = p->next;
            p->next = NULL;
            p = t;
            t = t->next;
            p->next = NULL;
            while(t)
            {
                q = t->next;
                t->next = p;
                p = t;
                t = q;
            }
            t = head;
            while(p&&t)
            {
                q = p->next;
                p->next = t->next;
                t->next = p;
                t = t->next->next;
                p = q;
            }
        }
    };
  • 相关阅读:
    一键java环境配置
    eclipse + tomcat7 + maven 配置过程
    eclipse/myeclipse link 方式安装插件
    eclipse maven plugin 插件 安装 和 配置
    Spring MVC 教程,快速入门,深入分析
    Spring MVC 框架搭建及详解
    Javassist介绍
    OO的奇妙冒险4
    OO的奇妙冒险3
    OO的奇妙冒险2
  • 原文地址:https://www.cnblogs.com/727713-chuan/p/3409042.html
Copyright © 2011-2022 走看看