zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第二章 链表问题 按照左右半区的方式重新组合成新链表

    样例

    链表:1 2 3 4 5 6 7 8 9 10 前半部和后半部重新组合,结果:1 6 2 7 3 8 4 9 5 10
    

    java代码

    * @Description:按照左右半区的方式重新组合成新链表
     * @Author: lizhouwei
     * @CreateDate: 2018/4/7 17:45
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter2_20 {
        public Node relocation(Node head) {
            if (head == null) {
                return null;
            }
            Node node1 = head;
            Node node2 = head; //node2 以head开始 ,或者以 head.next开始,最终node1都是链表的中间节点
            //node1走一步,node2走两步,当node2.next.next走到结尾的时候node1所在的位置为链表的中间节点
            //例如:链表为 1-2-3-4-5-6-7-8-9-10 node1=5,node2=9时,node1为中间节点
            while (node2.next != null && node2.next.next != null) {
                node1 = node1.next;
                node2 = node2.next.next;
            }
            node2 = node1.next;
            node1.next = null;
            node1 = head;
            Node next = null;
            while (node1 != null) {
                next = node2.next;//node2的后继节点
                node2.next = node1.next;//node2的后继节点指向node1的后继节点
                node1.next = node2;//node1的后继节点指向node2,node2插入到了原始node1和node1.next中间了
                node1 = node2.next;//取出原始node1的后继节点,此时是node2的后继节点
                node2 = next;
            }
            return head;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter2_20 chapter = new Chapter2_20();
            Link link = new Link();
    
            //构造链表
            for (int i = 10; i > 0; i--) {
                link.add(i);
            }
            Link.printLink(link.head);
            Node head = chapter.relocation(link.head);
            Link.printLink(head);
        }
    }
    
  • 相关阅读:
    hdu1828线段树(两次扫描+离散化)
    hdu1542线段树(扫描线+离散化)
    二分思想
    hdu2871线段树区间更新
    git初体验
    python笔记-模块
    python笔记-动态类型
    AWS上创建EKS(K8S)集群
    Akamai CDN刷新(通过Akamai cli 自动刷新)
    创建Akamai cdn api授权
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8734075.html
Copyright © 2011-2022 走看看