zoukankan      html  css  js  c++  java
  • 138 Copy List with Random Pointer 复制带随机指针的链表

    给出一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
    返回一个深拷贝的链表。
    详见:https://leetcode.com/problems/copy-list-with-random-pointer/description/

    Java实现:

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if(head==null){
                return null;
            }
            RandomListNode cur=head;
            Map<RandomListNode,RandomListNode> m=new HashMap<RandomListNode,RandomListNode>();
            while(cur!=null){
                m.put(cur,new RandomListNode(cur.label));
                cur=cur.next;
            }
            cur=head;
            while(cur!=null){
                m.get(cur).next=m.get(cur.next);
                m.get(cur).random=m.get(cur.random);
                cur=cur.next;
            }
            return m.get(head);
        }
    }
    
  • 相关阅读:
    Swift-基础语法之变量&常量&元组
    Swift
    安装MySQL
    LNMP 简介
    LNMP
    Django 定义数据模型
    Django 添加应用
    Django 创建第一个项目
    Django 安装
    Django 简介
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8724769.html
Copyright © 2011-2022 走看看