• 剑指Offer——复杂链表的复制


    1、题目描述

      输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

    2、代码实现

    package com.baozi.offer;
    
    import java.util.HashMap;
    
    /**
     * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),
     * 返回结果为复制后复杂链表的head。
     * (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
     *
     * @author BaoZi
     * @create 2019-07-12-19:42
     */
    public class Offer21 {
        public static void main(String[] args) {
            Offer21 offer21 = new Offer21();
            RandomListNode r1 = new RandomListNode(1);
            RandomListNode r2 = new RandomListNode(2);
            RandomListNode r3 = new RandomListNode(3);
            RandomListNode r4 = new RandomListNode(4);
            RandomListNode r5 = new RandomListNode(5);
            r1.next = r2;
            r2.next = r3;
            r3.next = r4;
            r4.next = r5;
            r5.next = null;
            r1.random = r3;
            r2.random = r4;
            r3.random = r2;
            r4.random = r2;
            r5.random = r1;
            RandomListNode clone = offer21.Clone(r1);
            RandomListNode temp = clone;
            while (temp != null) {
                System.out.println(temp.label+"--" + temp.random.label);
                temp = temp.next;
            }
    
        }
    
        public RandomListNode Clone(RandomListNode pHead) {
            if (pHead == null) {
                return null;
            }
            RandomListNode newHead = new RandomListNode(pHead.label);
            HashMap<RandomListNode, RandomListNode> hashmap = new HashMap<>();
            hashmap.put(pHead, newHead);
            RandomListNode temp_newHead = newHead;
            RandomListNode temp_pHead = pHead.next;
            while (temp_pHead != null) {
                RandomListNode temp = new RandomListNode(temp_pHead.label);
                hashmap.put(temp_pHead, temp);
                temp_newHead.next = temp;
                temp_newHead = temp_newHead.next;
                temp_pHead = temp_pHead.next;
            }
            temp_pHead = pHead;
            while (temp_pHead != null) {
                hashmap.get(temp_pHead).random = hashmap.get(temp_pHead.random);
                temp_pHead = temp_pHead.next;
            }
            return newHead;
        }
    
    }
    
    class RandomListNode {
        int label;
        RandomListNode next = null;
        RandomListNode random = null;
    
        RandomListNode(int label) {
            this.label = label;
        }
    }
    

      

  • 相关阅读:
    websocket协议
    LeakCanary 中文使用说明
    编程习惯1
    Spring事务管理(详解+实例)
    微信 JS API 支付教程
    mi面试题
    最锋利的Visual Studio Web开发工具扩展:Web Essentials详解(转)
    .Net 高效开发之不可错过的实用工具
    手机版开发框架集合
    node.js建立简单应用
  • 原文地址:https://www.cnblogs.com/BaoZiY/p/11178211.html
Copyright © 2020-2023  润新知