zoukankan      html  css  js  c++  java
  • LeetCode143. 重排链表

    思路:

    1. 快慢指针找到中间节点,切成两半。(注意链表长度的奇偶性)
    2. 后半部分 reverse 操作。
    3. 归并操作,即后半部分 塞到 前半部分的“缝隙”里,组成新的链表。
    class Solution {
        public void reorderList(ListNode head) {
            if (head == null || head.next == null) return;
            // Step1. 找到中间节点
            ListNode fast = head, slow = head;
            while (fast.next != null && fast.next.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
    
            // Step2:切成两半,后半部分reverse
            ListNode l2 = slow.next;
            slow.next = null;
            l2 = reverse(l2);
            ListNode l1 = head;
    
            // Step3:后半部分塞到 前半部分的"缝隙"里
            while (l1 != null && l2 != null) {
                ListNode next1 = l1.next;
                l1.next = l2;
                ListNode next2 = l2.next;
                l2.next = next1;
    
                l1 = next1;
                l2 = next2;
            }
        }
        // 反转链表
        private ListNode reverse(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode cur = head;
            ListNode pre = null, next = null;
            while (cur != null) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
    }
  • 相关阅读:
    周记 2016.3.29
    Java ActiveMQ 讲解(一)理解JMS 和 ActiveMQ基本使用(转)
    聊聊架构01
    乐观锁和悲观所
    数据库锁(转)
    ActiveMQ消息的可靠性机制(转)
    DOM
    JavaScript
    CSS之background
    CSS之overflow
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14135688.html
Copyright © 2011-2022 走看看