zoukankan      html  css  js  c++  java
  • LeetCode Copy List with Random Pointer

    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

    Return a deep copy of the list.

    题目意思是复制一个节点带有随机指针的链表。

    方法是先把链表放入LIST内,然后遍历list为每个节点添加随机指针。

    /**
     * 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;
            }
            ArrayList<RandomListNode> oldList=new ArrayList<>();
            ArrayList<RandomListNode> newList=new ArrayList<>();
            int indexRandom;
            RandomListNode tempNode=head;
            while (tempNode!=null) {
                oldList.add(tempNode);
                newList.add(new RandomListNode(tempNode.label));
                tempNode=tempNode.next;
            }
            for (int i = 0; i < oldList.size(); i++) {
                if (i<oldList.size()-1) {
                    newList.get(i).next=newList.get(i+1);
                }
                indexRandom=oldList.indexOf(oldList.get(i).random);
                if (indexRandom>=0) {
                    newList.get(i).random=newList.get(indexRandom);
                }
            }
            
            return newList.get(0);
        }
    }
  • 相关阅读:
    PHP 速度测试函数
    ajax的简单应用之快速入门
    PHP漏洞详解
    jQuery Ajax 实例 全解析
    2007年最后的一天
    近来心情格外的郁闷
    使用 Ajax 实现 lightbox
    GridView删除,编辑应用
    完美的wsus客户端注册表文件
    VISTA桌面显示Internet Explorer
  • 原文地址:https://www.cnblogs.com/birdhack/p/3950465.html
Copyright © 2011-2022 走看看