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;
            }
        }
    };
  • 相关阅读:
    line-block,white-space,overflow
    JS操作cookie
    C#的位运算
    小常识:变量的修饰符和DEMO
    JS等号的小注释
    关于谷歌浏览器的小常识
    P2568 GCD
    P2522 [HAOI2011]Problem b
    P3455 [POI2007]ZAP-Queries
    P1447 [NOI2010]能量采集
  • 原文地址:https://www.cnblogs.com/727713-chuan/p/3409042.html
Copyright © 2011-2022 走看看