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

    将给定的单链表 L L: L_0→L_1→…→L_{n-1}→L_ nL0L1Ln1Ln
    重新排序为:L_0→L_n →L_1→L_{n-1}→L_2→L_{n-2}→…L0LnL1Ln1L2Ln2
    要求使用原地算法,不能改变节点内部的值,需要对实际的节点进行交换。
    例如:
    对于给定的单链表{10,20,30,40},将其重新排序为{10,40,20,30}.

    思路:

    1,找到链表的中间节点

    2,反转后面的链表

    3,归并的方式合并前后链表

    4,注意最后需要将前链表的最后一个节点的next改为null,否则会有环

    代码

    private static void reorderList(ListNode head) {
            if (head == null || head.next == null) {
                return;
            }
            ListNode fast = head;
            ListNode slow = head;
            while (fast.next != null && fast.next.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            ListNode after = slow.next;
            ListNode pre = null;
            while (after != null) {
                ListNode temp = after.next;
                after.next = pre;
                pre = after;
                after = temp;
            }
            ListNode first = head;
            after = pre;
            while (after != null) {
                ListNode fTemp = first.next;
                ListNode aTemp = after.next;
                first.next = after;
                after.next = fTemp;
    
    
                first = fTemp;
                after = aTemp;
    
    
            }
    
            first.next = null;
    
            System.out.println(0);
        }
  • 相关阅读:
    FZU 2113 BCD Code 数位dp
    Gym 100917L Liesbeth and the String 规律&&胡搞
    Gym 100917C Constant Ratio 数论+暴力
    CF149D Coloring Brackets
    P4342 [IOI1998]Polygon
    P4316 绿豆蛙的归宿
    P1439 【模板】最长公共子序列
    Noip 2013 真题练习
    洛谷比赛 「EZEC」 Round 4
    P5024 保卫王国
  • 原文地址:https://www.cnblogs.com/dongma/p/14199836.html
Copyright © 2011-2022 走看看