zoukankan      html  css  js  c++  java
  • Leetcode 143. Reorder List

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-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}.


    Analysis:

    1. Break list in the middle to two lists (use fast & slow pointers)
    2. Reverse the order of the second list
    3. Merge two list back together

    Java code:

    20160601

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void reorderList(ListNode head) {
            //1.find the middle node in the list and split it into two small list
            //2. reverse the second list
            //3. merge two halves into one long list
            
            //base case
            if(head == null || head.next == null) {
                return;
            }
            
            ListNode mid = findMiddle(head);
            ListNode one = head;
            ListNode two = mid.next;
            mid.next = null;
            two = reverse(two);
            merge(one, two);
        }
        
        private ListNode findMiddle(ListNode head) {
            if(head == null || head.next == null) {
                return head;
            }
            ListNode slow = head, fast = head;
            while(fast.next != null && fast.next.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            return slow;
        }
        
        private ListNode reverse(ListNode head) {
            //iteration
            if(head == null || head.next == null) {
                return head;
            }
            ListNode pre = null;
            ListNode cur = head;
            while(cur != null) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
        
        private void merge(ListNode one, ListNode two) {
            while(two != null) {
                ListNode next1 = one.next;
                ListNode next2 = two.next;
                one.next = two;
                two.next = next1;
                one = next1;
                two = next2;
            }
        }
    }
  • 相关阅读:
    Swagger+IdentityServer4测试授权验证
    IdentityServer4使用EFCore生成MySql时的小bug
    Ocelot + IdentityServer4 构建 GateWay
    使用Ocelot构建GateWay
    MediatR 中介模式
    EFCore CodeFirst 适配数据库
    Mysql 主从配置
    IdentityServer4揭秘---Consent(同意页面)
    idea 启动时报 error:java 无效的源发行版11
    centos mysql数据库忘记密码修改
  • 原文地址:https://www.cnblogs.com/anne-vista/p/5551702.html
Copyright © 2011-2022 走看看