138. Copy List with Random Pointer

来源:互联网 发布:膛线管55淘宝400元 编辑:程序博客网 时间:2024/05/16 18:33

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.



import java.util.ArrayList;import java.util.List;public class Solution {//List<Integer> randPos = new ArrayList<Integer>();List<RandomListNode> nowList = new ArrayList<RandomListNode>();List<RandomListNode> newList = new ArrayList<RandomListNode>();    public RandomListNode copyRandomList(RandomListNode head) {        if(head == null)return null;                RandomListNode dummy = new RandomListNode(0);        RandomListNode tmp1 = head, tmp2 = dummy;        while(tmp1 != null) {        nowList.add(tmp1);        tmp2.next = new RandomListNode(tmp1.label);        newList.add(tmp2.next);                tmp1 = tmp1.next;        tmp2 = tmp2.next;        }                tmp1 = head; tmp2 = dummy.next;        while(tmp1 != null) {        int pos = nowList.indexOf(tmp1.random);        if(pos != -1)        tmp2.random = newList.get(pos);                tmp1 = tmp1.next;        tmp2 = tmp2.next;        }                return dummy.next;            }}


0 0