zoukankan      html  css  js  c++  java
  • 链表五:复杂链表的复制

    /**
     * 题目:复杂链表的复制
     * 描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。
     *   (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
     * 方案:方法一:  ① 遍历原链表,每次创建新节点,放入到HashMap里面;
     *     ② 遍历,进行节点连接; 
     *     ③ HashMap中,Value对应的值就是复制的链表
     *           方法二:  将原链表和复制的链表先放到一起,然后在进行拆分
     * */

    public class Five {
        
        public static RandomListNode one(RandomListNode phead) {
            HashMap<RandomListNode, RandomListNode> hashMap  =  new HashMap<>();
            RandomListNode cur;
            cur = phead;
            while(cur != null) {
                hashMap.put(cur, new RandomListNode(cur.label));
                cur = cur.next;
            }
            cur = phead;
            while(cur != null) {
                hashMap.get(cur).next = hashMap.get(cur.next);
                hashMap.get(cur).random = hashMap.get(cur.random);
                cur = cur.next;
            }
            return hashMap.get(phead);
        }
        public static RandomListNode two(RandomListNode phead) {
            if(phead == null) {
                return null;
            }
            RandomListNode current = phead;
            //1.复制节点到A与B之间   A  A*  B  , 连接任意节点和next节点
            while(current !=null) {
                RandomListNode cloneNode = new RandomListNode(current.label); 
                RandomListNode nextNode = current.next;
                RandomListNode randomNode = current.random == null? null:current.random ;
                cloneNode.next = nextNode;
                current.next = cloneNode;
                cloneNode.random = randomNode;
                current = nextNode;
            }
            
            //拆分
            current = phead;
            RandomListNode pCloneHead = phead.next;
            while(current !=null ) {
                RandomListNode cloneNode = current.next;
                current.next = cloneNode.next;
                cloneNode.next = phead.next.next == null?null:phead.next.next;
                current = current.next;
            }
                return null;
        }
        
        static class RandomListNode{    
            int label;
            RandomListNode next;
            RandomListNode random;
            public RandomListNode(int label) {
                super();
                this.label = label;
            }
        }
    }
    天助自助者
  • 相关阅读:
    优化cocos2d/x程序的内存使用和程序大小
    cocos2d-x移植:xcode到eclipse
    程序员在编程工作中痛苦的压抑着自己某些强烈的情绪
    C++语言的一些问题
    基数排序-图非常清晰明了
    【Cocos2d-X(1.x 2.x) 修复篇】iOS6 中 libcurl.a 无法通过armv7s编译以及iOS6中无法正常游戏横屏的解决方法
    《C++ Primer》笔记-inline内联函数
    走出你的舒适区
    UDP广播与多播
    测试问题反馈需要包含内容总结
  • 原文地址:https://www.cnblogs.com/ZeGod/p/9969342.html
Copyright © 2011-2022 走看看