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); } }