zoukankan      html  css  js  c++  java
  • Reorder List

    Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln

    reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

    Example

    Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

    分析



    首先使用快慢指针找到list的中间数
    1->2->3->4->null返回的2
    1->2->3->4->5->null返回的3
    1->2->3->4->5->6->null返回的3
    可以使用 Middle of Linked List 中的函数

    然后将中间数的后面的 ListNode 反序

    之后挨个合并就是
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */ 
    public class Solution {
        /**
         * @param head: The head of linked list.
         * @return: void
         */
        public void reorderList(ListNode head) {  
            // write your code here
            if(head == nullreturn;
            // find mid node
            ListNode slow = head, fast = head;
            while(fast != null && fast.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
            // reverse the right half list
            ListNode pos2 = reorder(slow.next);
            ListNode pos1 = head;
            slow.next = null;
             
            // combine the two list to one
            ListNode dummy = new ListNode(0);
            ListNode pos = dummy;
            boolean sign = false;
            while(pos2 != null){
                pos.next = sign ? pos2 : pos1;
                 
                if(sign)
                    pos2 = pos2.next;
                else
                    pos1 = pos1.next;
                     
                pos = pos.next;
                sign = !sign;
            }
            pos.next = pos1;
        }
         
        public ListNode reorder(ListNode head){
            ListNode dummy = null;
            ListNode pos = dummy;
            ListNode next = head;
            while(next != null){
                ListNode tmp = next.next;
                next.next = pos;
                pos = next;
                next = tmp;
            }
            return pos;
        }
    }




  • 相关阅读:
    java基础知识
    21-树形结构菜单之封装递归组件
    05-写vue中的一些小细节
    20-Mock拦截ajax请求,模拟数据
    19-count-to数字滚动组件封装
    18-简单封装axios
    04-Vscode-setting设置
    17-vue给有需要的路由设置title
    03-vuecli中的.editorconfig文件
    06-npm下载依赖存放位置修改
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/1fafa371ac567c679b2ead206403034e.html
Copyright © 2011-2022 走看看