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);
        }
    }
  • 相关阅读:
    Coursera Algorithm II PA2 Q2
    Coursera Algorithm Part II PA2
    实现 memcpy 函数
    超人
    Proxy 模式
    【6】锋利的 jQuery 笔记
    【3】Chrome 的一些常用操作
    HTML 待解决与已解决问题
    CSS 待解决问题
    JS 一些常用技巧
  • 原文地址:https://www.cnblogs.com/birdhack/p/3950465.html
Copyright © 2011-2022 走看看