zoukankan      html  css  js  c++  java
  • 剑指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;
        }
    }
    

      

  • 相关阅读:
    USB HID Report Descriptor 报告描述符详解
    USB 管道 && 端点
    USB描述符解析-->枚举.
    USB HID介绍
    USB2.0速度识别
    spring core
    好妈妈【第三章】一生受用的品格教育,不止孩子需要,父母也需要。
    好妈妈【第二章】把学习做成轻松的事,父母如何提升孩子的学习成绩
    好妈妈【第一章】提高爱的质量,小学前的儿童教育
    Java日志系统
  • 原文地址:https://www.cnblogs.com/BaoZiY/p/11178211.html
Copyright © 2011-2022 走看看